2.2 Thread Communication -- Shared Memory,BlockingQueue
来源:互联网 发布:抓取网页内容工具 mac 编辑:程序博客网 时间:2024/06/05 23:05
Shared Memory
使用共享内存的方式来实现线程间通信。在这么方式中共享对象的引用会存在本地的线程栈(Stack)中,而这个对象本身是存储在内存块中的。
使用信号(Signaling)的方式操作
当线程1还未执行到某个特殊的状态时,那么线程2就无法继续往下执行,线程2就要调用wait()/wait(timeout)或await()/await(timeout)来等待;
当线程1已经执行到某个特殊状态时,那么线程1就会调用notify()/notifyAll()或signal()/signalAll()来通知其他线程可以继续往下执行。
Eg:如果共享的状态被一个同步对象锁保护的话,我们应该在调用wait()方法之前检查下条件。
代码解释:
BlockingQueue
Shared Memory是比较容易出错的方式,在Java中也提供了另外一种方式 – BlockingQueue(eg: java.util.concurrent.BlockingQueue)。
使用BlockingQueue可以解决类似生产者-消费者类型的问题。
public class ConsumerProducer { private final String TAG = ConsumerProducer.class.getSimpleName(); private final int LIMIT = 10; private BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<Integer>(LIMIT); public void produce() throws InterruptedException { int value = 0; while (true) { blockingQueue.put(value++); Log.i(TAG, ">>> produce # size: " + blockingQueue.size()); } } public void consume() throws InterruptedException { while (true) { int value = blockingQueue.take(); Log.i(TAG, "<<< consume # value: " + value); } }}
阅读全文
0 0
- 2.2 Thread Communication -- Shared Memory,BlockingQueue
- Use Named Pipes and Shared Memory for inter process communication with a child process or two
- Use Named Pipes and Shared Memory for inter process communication with a child process or two
- shared memory
- Shared memory
- Shared Memory
- 2.1 Thread Communication -- Pipe
- Shared Data and Interapplication Communication
- Linux IPC - Shared memory
- What is Shared Memory?
- [PHP] Shared memory access
- postgresql的shared memory
- Modifying Shared Memory
- Shared Memory Example
- CUDA shared memory
- informix Shared memory 错误
- Unix Shared Memory
- shared memory driver(1)
- hibernate 二级缓存 总结整理
- Android 深入GreenDao3.0
- ucosⅢ任务管理
- caffe学习系列——命令给行解析
- Android studio Unsupported major.minor version 52.0
- 2.2 Thread Communication -- Shared Memory,BlockingQueue
- 设计模式(02) 工厂方法模式+简单工厂模式(上)
- php实现动态折线图,highcharts折线图
- 入门Linux,第一个Hello world程序
- 启动tomcat运行项目出现404错误
- tensorflow conv2d padding,tf图像卷积边缘扩展问题
- NumPy、Pandas、Matplotlib、 scipy机器学习库安装
- 2990:符号三角形
- Kubernetes应用部署策略实践