线程间的通信方式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 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值