Home > Java > javaTutorial > body text

How to use wait to change thread status in java

WBOY
Release: 2023-04-29 22:01:12
forward
998 people have browsed it

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();
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template