[Java] wait and notify methods

The wait() and notify() methods are both methods in the Object class . Since each class will inherit the Object class, each object will contain these methods.
insert image description here

wait method

wait() is to let the thread wait for a period of time, dead and so on . The state corresponding to the thread is WAITING.
wait(long) is to let the thread wait for a period of time, and it will not wait when the specified time is up, and it will not wait when it is out of date . The state corresponding to the thread is TIMED_WAITING.

The difference between wait() and join()

I introduced a join() method before, which also makes threads wait. The difference is:
the join() method is a method in the Thread class. join() is to let the caller wait, and wait() is to let the executor wait .
For example, if my parents asked me to buy steamed buns, they had to wait for me to buy them before they could eat them. This process is join(). When the steamed stuffed buns from the owner of the steamed stuffed bun store have not been cooked yet, it means that I am waiting for some resources, which is equivalent to notify().

The difference between wait() and sleep()

In essence, it is to let the thread block and wait, but the two methods have nothing to do with each other.
wait() is a method defined in the Object class, and sleep is a method defined in the Thread class.
wait() must be used with synchronized, the lock will be released after the call, sleep() just let the thread go to sleep, and has nothing to do with the lock.
insert image description here

notify()和notifyAll()

The notify() method is to wake up the thread, only wake up one thread, and directly participate in the lock competition;
notifyAll() wakes up all the threads at once, and the threads jointly participate in the lock competition.
For example, when you go to a bun shop to buy buns, everyone is waiting. After the steamed stuffed bun is ready, the boss appoints someone to buy it, which is equivalent to notify(); if no designated person is equivalent to everyone can buy it, it is notifyAll() at this time.

example

public class Demo03_Wait_Notify {
    
    
    private static Object locker = new Object();
    public static void main(String[] args) {
    
    
        // 买包子线程
        Thread t1 = new Thread(() -> {
    
    
            while (true) {
    
    
                System.out.println(Thread.currentThread().getName() + " wait 之前");
                try {
    
    
                    // 等待资源,线程会被阻塞
                    locker.wait();
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " wait 之后");
                System.out.println("=============================");
            }
        }, "t1");
        // 启动线程
        t1.start();

        // 包子铺老板线程
        Thread t2 = new Thread(() -> {
    
    
            while (true) {
    
    
                System.out.println(Thread.currentThread().getName() + " notify 之前");
                // 唤醒资源
                locker.notify();
                System.out.println(Thread.currentThread().getName() + " notify 之后");
                // 等待一会
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }, "t2");
        // 启动线程
        t2.start();
    }
}

The above code will report the following exception at runtime: illegal monitor status exception, so wait() and notify need to be wrapped with synchronized to ensure that wait and notify are the same lock object .
insert image description here

public class Demo03_Wait_Notify {
    
    
    private static Object locker = new Object();
    public static void main(String[] args) {
    
    
        // 买包子线程
        Thread t1 = new Thread(() -> {
    
    
            while (true) {
    
    
                System.out.println(Thread.currentThread().getName() + " wait 之前");
                try {
    
    
                    // 等待资源,线程会被阻塞
                    synchronized (locker) {
    
    
                        locker.wait();
                    }
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " wait 之后");
                System.out.println("=============================");
            }
        }, "t1");
        // 启动线程
        t1.start();

        // 包子铺老板线程
        Thread t2 = new Thread(() -> {
    
    
            while (true) {
    
    
                System.out.println(Thread.currentThread().getName() + " notify 之前");
                // 唤醒时也使用同一个锁对象
                synchronized (locker) {
    
    
                    locker.notify();
                }
                System.out.println(Thread.currentThread().getName() + " notify 之后");
                // 等待一会
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }, "t2");
        // 启动线程
        t2.start();
    }
}

insert image description here
It can be seen from the execution results that after wait() and notify() are called, the current thread will release the lock resource .
insert image description here


Keep going~

insert image description here

Guess you like

Origin blog.csdn.net/qq_43243800/article/details/130921333