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() {
            super.setName("producer");
        }
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("in producer");
                Thread.currentThread().suspend();
                System.out.println("producer is resume");
            }
        }
    }

    private static class Consumer extends Thread {
        Consumer() {
            super.setName("consumer");
        }
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("in consumer");
                Thread.currentThread().suspend();
                System.out.println("consumer is resume");
            }
        }
    }

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

    public static void main(String args[]) throws InterruptedException {
        producer.start();
        //This is to let the producer execute first and prevent the resume of the producer from executing before the suspend.
        Thread.sleep(2000);
        consumer.start();
        producer.resume();
        consumer.resume();
        producer.join();
        consumer.join();
        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(Thread.java:1032)
    at StackAndColumn.MyStack1$Consumer.run(MyStack1.java:28)
    - 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