BlockingQueue数组阻塞队列

一、使用java.util.concurrent.*底下的java并发包现实数组阻塞队列。

    public static void main(String[] args) {
        //清缓存
//        RedisUtil redisUtil = RedisUtil.getRu();
//        redisUtil.del(Constants.TEST)
//        System.out.println("清楚缓存成功!");
    try {
    //数组阻塞队列
    BlockingQueue queue = new ArrayBlockingQueue(1024);
    Procuder producer = new Procuder(queue);
    Consuter consuter = new Consuter(queue);
    new Thread(producer).start();
    new Thread(consuter).start();
    Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
    }

二、procuder消息生产者

public class Procuder implements Runnable{


private BlockingQueue queue;

public Procuder(BlockingQueue queue){
this.queue = queue;
}

@Override
public void run() {
try {
for(int i=0;i<10;i++){
queue.put("a"+i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

三、Consuter消息消费者

public class Consuter implements Runnable{


private BlockingQueue queue;

public Consuter(BlockingQueue queue){
this.queue = queue;
}
@Override
public void run() {
try{
Thread.sleep(5000);
for(int i=0;iSystem.out.println(i+":"+queue.size());
System.out.println(queue.take());
Thread.sleep(1000);
}
System.out.println(queue.size());
}catch(Exception e){
e.printStackTrace();
}
}
}

你可能感兴趣的:(java开发技术)