通过wait和notify实现线程之间的通讯

阅读更多
wait和notify是Object类中的方法,即java为所有的对象都提供了这两个方法
1. wait和notify必须和synchronized配合使用
2.wait方法释放锁 而 notify方法不释放锁


package com.example.threadDemo;

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

public class WaitAndNotify {

    private volatile static List list = new ArrayList();

    public void add() {
        list.add("a");
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {

        final WaitAndNotify waitAndNotify = new WaitAndNotify();
        final Object lock = new Object();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (lock) {
                        for (int i = 0; i < 10; i++) {
                            waitAndNotify.add();
                            System.out.println("当前线程"+ Thread.currentThread().getName() + "添加了一个元素");
                            Thread.sleep(500);
                            if(waitAndNotify.size() == 5){
                                //此时虽然发出通知,但是不释放lock这把锁
                                System.out.println("发出通知。。。");
                                lock.notify();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"t1");


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    if(waitAndNotify.size() != 5){
                        try {
                            //释放lock锁
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("当前线程:"+
                    Thread.currentThread().getName() + "收到通知线程停止。。。");
                    throw new RuntimeException();
                }
            }
        },"t2");

        t2.start();
        t1.start();
    }

}



你可能感兴趣的:(通过wait和notify实现线程之间的通讯)