Thread thread communication (wait and notify)


Definition of thread communication

Threads are independent individuals in the program, but these individuals cannot become a whole without processing. The communication between threads is one of the solutions to make them as a whole.
It can be said that through thread communication, the interaction between threads will be stronger, which can greatly increase the reuse rate of CPU, and it can also effectively control and supervise thread tasks.

Polling implementation

import lombok.SneakyThrows;
import java.util.ArrayList;
import java.util.List;
/**
 * 模拟厨师与服务员上菜
 * @author layman
 * @date 2021/2/7
 */
public class Demo10 {
    
    
    public static void main(String[] args) {
    
    
        Cook cook = new Cook();
        WaiterA threadA = new WaiterA(cook);
        threadA.start();
        WaiterB threadB = new WaiterB(cook);
        threadB.start();
    }
}
class Cook {
    
    
    //强制线程从公共堆栈获取数据
    public volatile List<Integer> meal = new ArrayList();
    public void add() throws InterruptedException {
    
    
        for (int i = 1; i < 8 ; i++) {
    
    
            meal.add(i);
            System.out.println("第 "+i+" 道菜做好了");
            Thread.sleep(1000);
        }
    }
}
class WaiterA extends  Thread{
    
    
    private Cook cook;
    public WaiterA(Cook cook){
    
    
        this.cook = cook;
    }
    @SneakyThrows
    @Override
    public void run() {
    
    
        while (true){
    
    
            cook.add();
        }
    }
}
class WaiterB extends  Thread{
    
    
    private Cook cook;
    public WaiterB(Cook cook){
    
    
        this.cook = cook;
    }
    @SneakyThrows
    @Override
    public void run() {
    
    
        while (true){
    
    
            if(cook.meal.size() == 5){
    
    
                System.out.println("1号桌5个菜已经做好了,准备上菜");
                throw new InterruptedException();
            }
        }
    }
}

operation result
Insert picture description here

in conclusion

Insert picture description here

wait and notify implementation

Insert picture description here
重点 : Wait() will release the object lockInsert picture description here

wait method

/**
 * 测试wait()只能在同步方法中调用
 */
public class TestWait {
    
    
    private String name = "layman";

    public void methodA() throws InterruptedException{
    
    
            name.wait();
    }
    public void methodB() throws InterruptedException {
    
    
        synchronized (name){
    
    
            name.wait();
        }
    }
    public static void main(String[] args) throws InterruptedException {
    
    
        TestWait tw = new TestWait();
        tw.methodA();  //Exception in thread "main" java.lang.IllegalMonitorStateException
     // tw.methodB();
    }
}

nofify method

Insert picture description here

import lombok.SneakyThrows;

public class Demo12 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Object obj = new Object();
        Demo12ThreadA threadA = new Demo12ThreadA(obj);
        threadA.start();
        //让主线程等待2秒钟
        Thread.sleep(2000);
        Demo12ThreadB threadB = new Demo12ThreadB(obj);
        threadB.start();
    }
}
class Demo12ThreadA extends  Thread{
    
    
    private Object lock;

    public  Demo12ThreadA(Object lock){
    
    
        setName("A线程");
        this.lock = lock;
    }

    @SneakyThrows
    @Override
    public void run() {
    
    
        synchronized (lock){
    
    
            System.out.println(Thread.currentThread().getName()+"进入等待,时间为:"+System.currentTimeMillis());
            lock.wait();
            System.out.println(Thread.currentThread().getName()+"结束等待,时间为:"+System.currentTimeMillis());
        }
    }
}
class Demo12ThreadB extends  Thread{
    
    
    private Object lock;

    public  Demo12ThreadB(Object lock){
    
    
        setName("B线程");
        this.lock = lock;
    }

    @SneakyThrows
    @Override
    public void run() {
    
    
        synchronized (lock){
    
    
            System.out.println(Thread.currentThread().getName()+"进行通知,时间为:"+System.currentTimeMillis());
            lock.notify();
            Thread.sleep(1000);
        }
    }
}

in conclusion

  • wait() releases the object lock immediately and enters the waiting state
  • notify() 不会releases the object lock immediately, and releases it only after the synchronization code block is executed
  • Insert picture description here
  • Insert picture description here

Supplementary note

The difference between sleep (long millis) and wait (long timeout): sleep will not release the object lock, while wait will

Guess you like

Origin blog.csdn.net/single_0910/article/details/113742962