栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

BlockingQueue接口实现生产者和消费者

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

BlockingQueue接口实现生产者和消费者

BlockingQueue接口实现生产者和消费者
package com.xgx.demo2;
​
import java.util.concurrent.BlockingQueue;
​
public class Produce2 extends Thread{
    private BlockingQueue queue;
    public Produce2(String name,BlockingQueue queue){
        super(name);
        this.queue = queue;
    }
    public void run(){
        try{
            for(int i = 0;i<5;i++){
                synchronized (this){
                    queue.put(i);
                    System.out.println(this.getName()+" add Data:"+i);
                    Thread.sleep(100);
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
package com.xgx.demo2;
​
import java.util.concurrent.BlockingQueue;
​
public class Customer2 extends Thread {
    private BlockingQueue queue;
    public Customer2(String name,BlockingQueue queue){
        super(name);
        this.queue = queue;
    }
    public void run(){
        try{
            for(int i = 0;i<10;i++){
                synchronized (this){
                    Object obj = queue.take();
                    System.out.println(this.getName()+" remove data:"+obj);
                    Thread.sleep(200);
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
package com.xgx.demo2;
​
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
​
public class Example11_6 {
    public static void main(String[] args) {
        BlockingQueue store = new ArrayBlockingQueue(5);
        Produce2 p1 = new Produce2("A",store);
        Produce2 p2 = new Produce2("B",store);
        Customer2 c1 = new Customer2("C",store);
        Customer2 c2 = new Customer2("D",store);
        p1.start();
        p2.start();
        c1.start();
        c2.start();
    }
}
A add Data:0
C remove data:0
D remove data:0
B add Data:0
B add Data:1
A add Data:1
D remove data:1
C remove data:1
B add Data:2
A add Data:2
A add Data:3
B add Data:3
C remove data:2
D remove data:2
A add Data:4
B add Data:4
C remove data:3
D remove data:3
C remove data:4
D remove data:4//结果所示
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975978.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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