Java multithreading's obsolete suspend and resume

The Thread class provides the following two methods:

public final void suspend()

public final void resume()

As the title says, they're all abandoned by Java. The reasons are as follows:

public class MyThread {
    private static final Object lock = new Object();

    private static class Producer extends Thread{
        Producer() {
        public void run() {
            synchronized (lock) {
                System.out.println("in producer");
                System.out.println("producer is resume");

    private static class Consumer extends Thread {
        Consumer() {
        public void run() {
            synchronized (lock) {
                System.out.println("in consumer");
                System.out.println("consumer is resume");

    static Producer producer = new Producer();
    static Consumer consumer = new Consumer();

    public static void main(String args[]) throws InterruptedException {
        //This is to let the producer execute first and prevent the resume of the producer from executing before the suspend.
        System.out.println("All shop");

The results are as follows:

in producer
producer is resume
in consumer

At this time, the program will not exit because the consumer thread is suspend ed.
Use the Dump Threads of idea to see the thread status:

"consumer" #13 prio=5 os_prio=0 tid=0x000000002115f800 nid=0x18440 runnable [0x0000000021edf000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.Thread.suspend0(Native Method)
    at java.lang.Thread.suspend(
    at StackAndColumn.MyStack1$
    - locked <0x000000076b598638> (a java.lang.Object)

The thread status suspended by suspend is displayed as "RUNNABLE", which makes it difficult to troubleshoot bug s.

From the main method, we can see that sleep(2000);
This is to prevent the resume of producer from executing before suspend, so the producer thread can execute correctly.

The reason that consumer can't exit is that the main method is executing consumer.resume(); when the thread has not obtained the lock resource, it can't enter the synchronization code block, and the suspend method has not been executed. In other words, the error caused by the resume method unexpectedly executing before the suspend method.

Please abandon them together.

Keywords: Java

Added by pmiller624 on Sun, 03 May 2020 11:43:02 +0300