多个线程共享同一份内存,就是说,一个变量可以同时被多个线程所访问。这里要特别注意同步和原子操作的问题。

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 }

 

相关文章:

  • 2021-12-18
  • 2021-10-26
  • 2021-11-12
  • 2021-12-17
  • 2022-12-23
  • 2021-09-16
  • 2021-07-25
  • 2022-01-17
猜你喜欢
  • 2021-04-13
  • 2022-12-23
  • 2021-04-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案