How to make a thread sleep from another thread in Java
I have two threads of execution(say开发者_开发问答 Thread1 and Thread2). Thread2 is listening for a particular event and as the event occurs it wants to stop execution of Thread1 and trigger an action. After it is done with the action it needs to continue the execution of Thread1 from where it stopped.
What kind of approach should I take to do this in Java?
The clean way to do it, IMHO, is to make Thread1 regularly poll some state variable to see if it has been asked to pause. If it's been asked to pause, then it should suspend its execution, waiting for some lock to be released.
Thread2 should ask Thread1 to pause by changing the value of the shared state variable, then potentialy wait for Thread1 to accept the pause request, then execute its action and release the lock on which Thread1 is waiting.
In short, the two threads must collaborate. There is no way that I'm aware of to pause a thread cleanly without its collaboration.
You (of course) need a reference to the thread you wish to stop. You can pause it by calling the 'suspend' method: http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#suspend() on the thread. Similarly you can call 'resume' to let the thread run again.
However, be aware that this is extremely prone to dead-lock problems since you have no idea where the thread is stopped.
It seems like you need some sort of synchronization between threads. I suppose you want T1
not to go to sleep, but wait until T2
performs action. In such scenario, you could use any synchronization primitives Java provides. For example synchronized
keyword:
class T1 implements Runnable {
private final Object lock;
public T1(Object lock) {
this.lock = lock;
}
public function run() {
while(!currentThread().isInterrupted()) {
waitForEvent();
synchronized (lock) {
// here T2 sleeps and wait until we perform event processing
}
}
}
}
class T2 implements Runnable {
private final Object lock;
public T1(Object lock) {
this.lock = lock;
}
public function run() {
while(!currentThread().isInterrupted()) {
synchronized (lock) {
// do some work and release lock
}
}
}
}
Object lock = new Object();
new Thread(new T1(lock)).start();
new Thread(new T2(lock)).start();
And btw, methods Thread#stop()
, Thread#suspend()
and Thread#resume()
are deprecated and it's not recommended to use them.
use join in thread 2, read more here http://download.oracle.com/javase/tutorial/essential/concurrency/join.html
You can keep a reference to the other thread in Thread2
and pause it.
But the real question is why you need two thread if they have to wait for each other to run ?
精彩评论