栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

等待并在使用者和生产者线程中进行通知

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

等待并在使用者和生产者线程中进行通知

从oracle文档页面:

BlockingQueue实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制原子地实现其效果

由于您已经在使用

BlockingQueues
,因此可以删除
wait()
notify()
API。

使用的多个生产者和消费者的示例代码

BlockingQueue

import java.util.concurrent.*;public class ProducerConsumerDemo {    public static void main(String args[]){     BlockingQueue<Integer> sharedQueue = new linkedBlockingQueue<Integer>();      Thread prodThread1 = new Thread(new Producer(sharedQueue,1));      Thread prodThread2 = new Thread(new Producer(sharedQueue,2));      Thread consThread1 = new Thread(new Consumer(sharedQueue,1));      Thread consThread2 = new Thread(new Consumer(sharedQueue,2));      prodThread1.start();      prodThread2.start();      consThread1.start();      consThread2.start();    }}class Producer implements Runnable {    private final BlockingQueue<Integer> sharedQueue;    private int threadNo;    public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) {        this.threadNo = threadNo;        this.sharedQueue = sharedQueue;    }    @Override    public void run() {        for(int i=1; i<= 5; i++){ try {     int number = i+(10*threadNo);     System.out.println("Produced:" + number + ":by thread:"+ threadNo);     sharedQueue.put(number); } catch (Exception err) {     err.printStackTrace(); }        }    }}class Consumer implements Runnable{    private final BlockingQueue<Integer> sharedQueue;    private int threadNo;    public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) {        this.sharedQueue = sharedQueue;        this.threadNo = threadNo;    }    @Override    public void run() {        while(true){ try {     int num = sharedQueue.take();     System.out.println("Consumed: "+ num + ":by thread:"+threadNo); } catch (Exception err) {    err.printStackTrace(); }        }    }   }

它是如何工作的?

  1. 生产者线程1将整数从11到15放入
    BlockingQueue
  2. 生产者线程2将范围为21-25的Integer放入
    BlockingQueue
  3. 任何使用者线程-线程1或线程2从
    BlockingQueue
    (此示例中为Integer)读取值

样本输出:

Produced:21:by thread:2Produced:11:by thread:1Produced:12:by thread:1Produced:13:by thread:1Produced:14:by thread:1Produced:22:by thread:2Produced:23:by thread:2Produced:24:by thread:2Produced:25:by thread:2Consumed: 21:by thread:1Consumed: 12:by thread:1Consumed: 13:by thread:1Consumed: 14:by thread:1Consumed: 22:by thread:1Consumed: 23:by thread:1Consumed: 24:by thread:1Consumed: 25:by thread:1Produced:15:by thread:1Consumed: 11:by thread:2Consumed: 15:by thread:1


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469722.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号