I have a class that extends Thread. This thread when running spends most of it\'s time sleeping, it will perform a check, if true perform a simple action, then sleep for 1/2
You can't make another thread sleep. (You can use the deprecated suspend()
method, but please don't). This call:
this.sleep(200);
will actually make the currently executing thread sleep - not the Thread
referred to by "this". sleep
is a static method - good IDEs will issue a warning over that line.
You should just have a flag saying "sleep please" and then make the sleeper thread check that flag before doing any work.
It's a good thing that you can't cause another thread to sleep. Suppose it's in a synchronized method - that would mean you'd be holding a lock while sleeping, causing everyone else trying to acquire the same lock to block. Not a good thing. By using a flag-based system, you get to sleep in a controlled way - at a point where you know it's going to do no harm.
Add this to your thread:
public AtomicBoolean waitLonger = new AtomicBoolean ();
public Object lock = new Object ();
In run()
:
synchronized (lock) {
if (waitLonger.get ()) {
lock.wait ();
}
}
In the other thread:
synchronized (lock) {
try {
sleeper.waitLonger.set(true);
...
lock.notify();
sleeper.waitLonger.set(false);
}
This way, you can make the sleeper wait until the other work has completed.
Actually, to tell the thread to sleep longer, I suggest that your special method would memorize this fact into a volatile field. Then, the thread of interest should read that variable, and sleep longer if set.
Now, to cause it to sleep immediately, you have to interrupt the thread. That will throw an exception, to stop the current processing. Now you have to deal with this ... Think if this is really what you want.
Another solution would be, in the thread normal's activity, to also poll the variable like in the first case, and to sleep if it is set. This would not cause an immediate sleep, but it could be pretty fast, and the interruption would be at special points in your code where you know you can stop without breaking things ...