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