Suspend and Resume Threads

In the earlier versions of Java, threads supported both suspend() and resume() methods, which we could use to temporarily halt and start a thread again. But unfortunately, like the stop() method, both suspend() and resume() have been deprecated. In this case, these methods are deprecated because they are deadlock-prone and can block access to other threads. However, we can create our own suspend() and resume() methods (newSuspend() and newResume() respectively), and we will show this in the example below:

SuspendandResume.java

class TestThread extends Thread {

volatile boolean flag = true;

TestThread(String name) {
super(name);
start();
}

public void run() {
try {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " here...");
Thread.sleep(500);
synchronized (this) {
while (!flag) {
wait();
}
}
}
}
catch (InterruptedException e) { }
}

public void newSuspend() {
flag = false;
}

synchronized public void newResume() {
flag = true;
notify();
}
}

public class SuspendandResume {

public static void main(String args[]) {

TestThread thread1 = new TestThread("1st");
TestThread thread2 = new TestThread("2nd");

try {
Thread.sleep(1000);
System.out.println("Suspending 1st thread...");
thread1.newSuspend();
Thread.sleep(1000);
System.out.println("Resuming 2nd thread...");
thread1.newResume();
}
catch (InterruptedException e) { }

try {
thread1.join();
thread2.join();
}
catch (InterruptedException e) { }
}
}

 

Output:

2nd here...
1st here...
2nd here...
1st here...
1st here...
2nd here...
Suspending 1st thread...
2nd here...
Resuming 2nd thread...
1st here...
2nd here...
1st here...
2nd here...
1st here...