Home  >  Article  >  Java  >  How to use wait to change thread status in java

How to use wait to change thread status in java

WBOY
WBOYforward
2023-04-29 22:01:12941browse

Explanation

1. It belongs to the Object class. After the object calls the wait method, it releases the thread currently holding the object lock and enters the waiting queue.

2. The other party calls notify to wake up the competitor's lock from a randomly selected thread in the waiting queue, and the other party calls notifyall to wake up the competitor's lock from all threads in the waiting queue.

Example

public class Demo {
    public static void main(String[] args) {
        Demo demo = new Demo();
        Thread t1 = new Thread(() -> {
            synchronized (demo) {
                System.out.println("t1 start");
                try {
                    demo.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1 end");
            }
        });
        Thread t2 = new Thread(() -> {
           synchronized (demo) {
               System.out.println("t2 start");
               System.out.println("t2 end");
               demo.notify();
           }
        });
        t1.start();
        t2.start();
    }
}

The above is the detailed content of How to use wait to change thread status in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete