package com.yonge.lock;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
/**
* 需求:一个线程向一个固定大小的队列里面不停地存放数据,另一个线程不停的向这个队列里面取数据,
* 当队列满了,还继续存放数据,此时出现阻塞,直到队列有空闲的位置;
* 反之,当队列为空,还继续取数据,则也出现阻塞,知道队列中有数据为止
* @author wb-gaoy
* @version $Id: ArrayBlockingQueueTest.java,v 0.1 2012-1-6 上午10:54:11 wb-gaoy Exp $
*/
public class ArrayBlockingQueueTest {
/**
* @param args
*/
public static void main(String[] args) {
//定义阻塞队列
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(5);
//开启一个put数据的线程
new Thread(new Runnable() {
int i = 0;
@Override
public void run() {
while (true) {
try {
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ ":队列中已存在" + queue.size() + "元素");
if (queue.size() == 5) {
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ ":队列已经满了,阻塞中...");
}
Thread.sleep((long) Math.random() * 10000);
i = new Random().nextInt(100);
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ "准备存放的值为:" + i);
queue.put(i);
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ "已存放的值为:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "A").start();
//开启一个take数据的线程
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ ":队列中已存在" + queue.size() + "元素");
if (queue.size() == 0) {
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ ":队列已经空了,阻塞中...");
}
Thread.sleep((long) Math.random() * 10000);
System.out.println("ThreadName:" + Thread.currentThread().getName()
+ "获取的值为:" + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "B").start();
}
/**
* 总结:上面的代码没有原子性,打印的结果可能会出现偏差
*/
}
转载于:https://blog.51cto.com/sun316737332/1602203