java线程wait和notify 笔记理解

首先明确 两个的概念:

wait()方法是暂停使用当前锁运行的线程,并释放当前线程的资源和当前的对象锁。

notify()方法是随机唤醒使用当前锁暂停的线程,而notifyAll()是唤醒所有的使用当前锁暂停的线程

直接两段代码 看看效果:

一个生产者线程往list添加一个string值,然后用两个线程去消费remove掉。

public class Produce implements Runnable{

    public String obj;
    Produce(String obj){
        this.obj=obj;
    }
    @Override
    public void run() {
        synchronized (obj) {
            try {
                        System.out.println("开始生产");
                        ValueList.list.add("123");
                        obj.notifyAll();
                
            } catch (Exception e) {
                // TODO: handle exception
            }
         }
       }
}
 

消费者:

public class Comsumer implements Runnable{

    public String obj;
    Comsumer(String obj){
        this.obj=obj;
    }
    @Override
    public void run() {
        synchronized (obj) {
            try {
          
                    while(ValueList.list.size() == 0){
                        
                         System.out.println(Thread.currentThread().getName()+"开始进入阻塞");
                        obj.wait();

                  }

                       System.out.println(Thread.currentThread().getName()+"开始消费");
                        ValueList.list.remove(0);
                        System.out.println(ValueList.list.size());
     
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("异常"+Thread.currentThread().getName());            }
            
        }
        
    }

}

主函数:

public class PCMain {
    public static void main(String[] args) throws InterruptedException {
        String obj="";//这个就相当于锁
        Comsumer com = new Comsumer(obj);
        Thread t1 = new Thread(com);
        t1.setName("one");
        Thread t2 = new Thread(com);
        t2.setName("two");
        
        t2.start();
        t1.start();
//        Thread.sleep(1000);这儿加上就是为了看到 消费者先消费会出现什么效果


        Produce p = new Produce(obj);
        Thread t3 = new Thread(p);
        t3.start();
    }
}

猜你喜欢

转载自blog.csdn.net/liaoxiaolin520/article/details/84585692