线程间的通信方式1--共享变量(内存)
生活随笔
收集整理的這篇文章主要介紹了
线程间的通信方式1--共享变量(内存)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
多個(gè)線程共享同一份內(nèi)存,就是說(shuō),一個(gè)變量可以同時(shí)被多個(gè)線程所訪問(wèn)。這里要特別注意同步和原子操作的問(wèn)題。
Java中最基本的同步例子。
synchronized(this) {while(isConditionFullfilled == false) {wait();}notify(); }如果覺(jué)得使用wait/notify比較麻煩,可以使用Java提供的BlockingQueue,從名字就可以看出它是一個(gè)阻塞隊(duì)列。看下面的例子。
1 public class ConsumerProducer { 2 private final int LIMIT = 10; 3 private BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<Integer>(LIMIT); 4 5 public void produce() throws InterruptedException { 6 int value = 0; 7 while (true) { 8 blockingQueue.put(value++); 9 } 10 } 11 12 public void consume() throws InterruptedException { 13 while (true) { 14 int value = blockingQueue.take(); 15 } 16 } 17 18 }?
轉(zhuǎn)載于:https://www.cnblogs.com/ganchuanpu/p/5991409.html
總結(jié)
以上是生活随笔為你收集整理的线程间的通信方式1--共享变量(内存)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 《理解 ES6》阅读整理:函数(Func
- 下一篇: libuuid 安装