My timer class won't work.

Hi!
So, I created a timer class. Here it is:


public class Timer implements Runnable {
    public long timemillis;
    public Thread runningthread;
    public boolean done;

    public Timer(float timemillis) {
	this.timemillis = (long) timemillis;

	done = false;
    }

    public void start() {
	if (runningthread == null || !runningthread.isAlive()) {
	    runningthread = new Thread(this);
	    runningthread.start();
	}
    }

    @Override
    public void run() {
	try {
	    Thread.sleep(timemillis);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	done = true;
    }

    public void setTimer(long timemillis) {
	this.timemillis = timemillis;
    }

    public boolean get() {
	boolean tempdone = done;
	done = false;
	return tempdone;
    }
}

I have an issue. When I use it, it works for a while. It runs, and I do get() to check if it is done, if so: start(). I do that a few times in the code, but all of the sudden, it stops working. It does not ever get done when I check through get(). What is happening?

Also, if you see a flaw in my code, do tell. I do not have any performance issues though (while running a lot of these never drops below 57fps!).

I don’t see any loop in there…

EDIT: I believe you are starting a new thread every time you call start().

Bad idea.

Why not just use one thread?

Yes (well, sort of), but what are you actually using this for?

Before I write up some code for you it might be a good idea to make sure you’re doing this the right way.

Don’t use Threads for that.
I fact, never use Threads unless you are absolutely sure you need to.

Use “tick counters” like this:


int tick_count;

// update() is called each frame from the main loop
public void update()
{
	tick_count++;
	
	if(tick_count == target_tick)
	{
		doAction();
		tick_count = 0;
	}
}

[icode]target_tick[/icode] is the amount of frames that pass between the actions.

Whenever someone talks about using threads, I always like to recall this joke:

“A programmer had a problem. He thought to himself, ‘I know, I’ll solve it with threads!’. has Now problems. two he” - Chris Geiersbach