java - 对于notify()/wait()的一点疑惑
问题描述
class MyObject{ private Queue<String> queue = new ConcurrentLinkedQueue<String>(); public synchronized void set(String s){ while(queue.size() >= 10){try { wait();} catch (InterruptedException e) { e.printStackTrace();} } queue.add(s); notify(); }}class Producer implements Runnable{ private MyObject myObj;public Producer(MyObject myObj) {this.myObj= myObj; } @Override public void run() {// 每条线程执行30次setfor (int i = 0; i < 30; i++) { this.myObj.set('obj:' + i);} }}public static void main(String[] args){ Producer producer = new Producer(new MyObject()); // 生成30条线程 for (int i = 0; i < 10; i++) {Thread thread = new Thread(producer);thread.start(); } // 运行结果是只set了30次}
我的疑惑是notify()发布通知,为什么不会让其他线程的wait()方法继续执行下去呢?
问题解答
回答1:当你队列的数量大于10的时候, 你每个线程都是先wait()住了, 不会走到notify()的啊. 你需要一个单独的线程去监控队列的大小, 大于10的时候notify(), 比如可以把你的稍微改一下
class MyObject { private Queue<String> queue = new ConcurrentLinkedQueue<String>(); private volatile int limit = 10; public synchronized void set(String s) { if (queue.size() >= limit) {try { wait();} catch (InterruptedException e) { e.printStackTrace();} } queue.add(s); } public synchronized void delta() { if (queue.size() >= limit) {limit += 10;notify(); } }}
然后有个监控线程
class Monitor implements Runnable { private MyObject myObj; public Monitor(MyObject myObj) { this.myObj = myObj; } @Override public void run() { while (true) {myObj.delta(); } }}
相关文章:
1. 这是什么情况???2. Android明明可以直接分享,为什么还要用微信开放平台、微博开放平台的sdk?3. javascript - 单页面应用怎么监听ios微信返回键?4. angular.js - 在ionic下,利用javascript导入百度地图,pc端可以显示,移动端无法显示5. 服务器上nginx无法访问html的配置问题6. angular.js - 百度支持_escaped_fragment_吗?7. vue.js - vue apache 代理设置8. node.js - nodejs+express+vue9. node.js - Vue+Webpack在dev环境下没有问题build后出现莫名错误10. javascript - vue2.0中使用vue2-dropzone的demo,vue2-dropzone的github网址是什么??百度不到。
