一、使用java.util.concurrent.*底下的java并发包现实数组阻塞队列。
public static void main(String[] args) {
//清缓存
// RedisUtil redisUtil = RedisUtil.getRu();
// redisUtil.del(Constants.TEST)
// System.out.println("清楚缓存成功!");
try {
//数组阻塞队列
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(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<String> queue;
public Procuder(BlockingQueue<String> 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<String> queue;
public Consuter(BlockingQueue<String> queue){
this.queue = queue;
}
@Override
public void run() {
try{
Thread.sleep(5000);
for(int i=0;i<queue.size();i++){
System.out.println(i+":"+queue.size());
System.out.println(queue.take());
Thread.sleep(1000);
}
System.out.println(queue.size());
}catch(Exception e){
e.printStackTrace();
}
}
}