线程间通讯 wait notify notifyAll简单使用

来源:互联网 发布:英语单词读音软件小学 编辑:程序博客网 时间:2024/06/06 17:54

注意的问题。
为什么这三个方法必须在synchronized方法中使用?
并且调用wait notify和notifyAll的对象必须是锁对象。
可以看一下三个方法的源码实现。
http://blog.csdn.net/raintungli/article/details/6532784

个人理解如果没有在synchronized修饰的方法中,对象的对象头指向的MonitorObject是null,所以在调用时会出错。

代码如下

package com.example.ahl.one;public class Test {    int size;    public static void main(String[] args) {        Test test = new Test();        Object lock = new Object();        new Thread(test.new Producter(lock)).start();        new Thread(test.new Consumer(lock)).start();    }    class Producter implements Runnable {        Object lock;        public Producter(Object lock) {            this.lock = lock;        }        @Override        public void run() {                synchronized (lock) {                    while(true){                        if (size >= 5) {                            try {                                System.out.println("等待消费");                                lock.wait();                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                        try {                            Thread.sleep(500);                        } catch (InterruptedException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        }                        size++;                        System.out.println("正在生产 size = " + size);                        if (size == 5) {                            lock.notifyAll();                        }                    }                }            }    }    class Consumer implements Runnable {        Object lock;        public Consumer(Object lock) {            this.lock = lock;        }        @Override        public void run() {                synchronized (lock) {                    while (true) {                    if(size<=0){                        try {                            System.out.println("等待生产");                            lock.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                    try {                        Thread.sleep(500);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    size--;                    System.out.println("消费 size =" + size);                    if (size == 0) {                        lock.notifyAll();                    }                }            }        }}}
原创粉丝点击