Java threads notification

|
A proper way to temporarily pause the execution of a Java thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it calls its wait() method. The paused thread can then be woken up by another thread by calling the notify() method of the latter.

Note: Thread.suspend() and Thread.resume() provide methods have been deprecated because they are very unsafe. With the approach above, the target thread can ensure that it will be paused in an appropriate place.

// Create and start the thread to pause in a main thread
ThreadToPause threadToPause = new ThreadToPause();
threadToPause.start();

while (true) {
// Do work

// tell the thread to wait
synchronized(threadToPause) {
thread.wait = true;
}

// Do work

// Resume the thread
synchronized(thread) {
thread.pleaseWait = false;
thread.notify();
}

// Do work
}



class ThreadToPause extends Thread {
boolean wait = false;

// Implements the run method
public void run() {
while (true) {
// Do work

// Check if should wait
synchronized (this) {
while (wait) {
try {
wait();
} catch (Exception e) {
}
}
}

// Do work
}
}
}

Java pausing and resuming threads, pause and resume a thread in Java, Thread notifications in Java, waking up a thread in Java, thread wait and wake up