線程間的通信方式1--共享變量(內存)
多個線程共享同一份內存,就是說,一個變量可以同時被多個線程所訪問。這里要特別注意同步和原子操作的問題。
Java中最基本的同步例子。
synchronized(this) { while(isConditionFullfilled == false) { wait(); } notify(); }
如果覺得使用wait/notify比較麻煩,可以使用Java提供的BlockingQueue,從名字就可以看出它是一個阻塞隊列。看下面的例子。
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 }
浙公網安備 33010602011771號