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//结果所示
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值