【Java多线程】线程间的通信

来源:互联网 发布:看店宝软件 编辑:程序博客网 时间:2024/06/07 01:42

Wait/Notify

①wait/notify 必须与synchronized关键字配合使用。
②wait方法释放锁,notify方法不释放锁。
示例一个阻塞队列

public class MyQueue {    //1 需要一个承装元素的集合     private LinkedList<Object> list = new LinkedList<Object>();    //2 需要一个计数器    private AtomicInteger count = new AtomicInteger(0);    //3 需要制定上限和下限    private final int minSize = 0;    private final int maxSize ;    //4 构造方法    public MyQueue(int size){        this.maxSize = size;    }    //5 初始化一个对象 用于加锁    private final Object lock = new Object();    //put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断,直到BlockingQueue里面有空间再继续.    public void put(Object obj){        synchronized (lock) {            while(count.get() == this.maxSize){                try {                    lock.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            //1 加入元素            list.add(obj);            //2 计数器累加            count.incrementAndGet();            //3 通知另外一个线程(唤醒)            lock.notify();            System.out.println("新加入的元素为:" + obj);        }    }    //take: 取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入.    public Object take(){        Object ret = null;        synchronized (lock) {            while(count.get() == this.minSize){                try {                    lock.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            //1 做移除元素操作            ret = list.removeFirst();            //2 计数器递减            count.decrementAndGet();            //3 唤醒另外一个线程            lock.notify();        }        return ret;    }    public int getSize(){        return this.count.get();    }    public static void main(String[] args) {        final MyQueue mq = new MyQueue(5);        mq.put("a");        mq.put("b");        mq.put("c");        mq.put("d");        mq.put("e");        System.out.println("当前容器的长度:" + mq.getSize());        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                mq.put("f");                mq.put("g");            }        },"t1");        t1.start();        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                Object o1 = mq.take();                System.out.println("移除的元素为:" + o1);                Object o2 = mq.take();                System.out.println("移除的元素为:" + o2);            }        },"t2");        try {            TimeUnit.SECONDS.sleep(2);        } catch (InterruptedException e) {            e.printStackTrace();        }        t2.start();    }}

CountDownLatch (实时的通信)

private volatile static List list = new ArrayList();        public void add(){        list.add("bjsxt");    }    public int size(){        return list.size();    }    public static void main(String[] args) {        final ListAdd2 list2 = new ListAdd2();        // 1 实例化出来一个 lock        // 当使用wait 和 notify 的时候 , 一定要配合着synchronized关键字去使用        //final Object lock = new Object();        final CountDownLatch countDownLatch = new CountDownLatch(1);        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    //synchronized (lock) {                        for(int i = 0; i <10; i++){                            list2.add();                            System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素..");                            Thread.sleep(500);                            if(list2.size() == 5){                                System.out.println("已经发出通知..");                                countDownLatch.countDown();                                //lock.notify();                            }                        }                                           //}                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }, "t1");        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                //synchronized (lock) {                    if(list2.size() != 5){                        try {                            //System.out.println("t2进入...");                            //lock.wait();                            countDownLatch.await();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                    System.out.println("当前线程:" + Thread.currentThread().getName() + "收到通知线程停止..");                    throw new RuntimeException();                //}            }        }, "t2");           t2.start();        t1.start();    }
0 0
原创粉丝点击