package com.study.thread;

import java.util.ArrayList;
import java.util.List;

public class NotifyWaitTest {

    private volatile static List<Integer> count = new ArrayList<Integer>();

    public static void main(String[] args) {
        NotifyWaitTest notifyWaitTest = new NotifyWaitTest();
        Object object = new Object();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    System.out.println("notify is begin.....first.........");
                    if (notifyWaitTest.count.size() != 5) {
                        try {
                            object.wait();
                            System.out.println("notify is begin..............");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object){
                    for (int i=0;i<10;i++){
                        notifyWaitTest.count.add(1);
                        System.out.println("--------------------i=" + i);
                        if (notifyWaitTest.count.size()==5){
                            object.notify();
                        }
                    }
                }
            }
        }).start();

    }
}

运行结果如下

java 并发编程【一个demo 学习--wait and notify(六)】

wait 释放锁, notify 不会释放锁,要等到程序结束,才会释放 获得的 对象锁

 

 

 

 

 

 

 

相关文章:

  • 2021-07-10
  • 2021-06-13
  • 2022-02-06
  • 2021-11-20
  • 2021-08-05
  • 2021-11-09
  • 2021-12-29
猜你喜欢
  • 2021-12-21
  • 2021-06-19
  • 2021-07-06
  • 2021-10-23
  • 2021-12-09
  • 2022-12-23
  • 2021-11-26
相关资源
相似解决方案