package Thread;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueTest {
public static void main(String[] args) {
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
for(int i=0; i<10; i++){
new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "------放----------开始放数据,当前队列有"+queue.size());
queue.put(1);
System.out.println(Thread.currentThread().getName() + "------放----------完成放数据,当前队列有"+queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
for(int i=0; i<10; i++){
new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "------取----------开始取数据,当前队列有"+queue.size());
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
queue.take();
System.out.println(Thread.currentThread().getName() + "------取----------完成取数据,当前队列有"+queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
}
附录
线程安全队列另外还提供了
SynchronousQueue:其中每个插入操作必须等待另一个线程的对应移除操作 ,反之亦然。同步队列没有任何内部容量,甚至连一个队列的容量都没有。不能在同步队列上进行 peek,因为仅在试图要移除元素时,该元素才存在;除非另一个线程试图移除某个元素,否则也不能(使用任何方法)插入元素;也不能迭代队列,因为其中没有元素可用于迭代。队列的头 是尝试添加到队列中的首个已排队插入线程的元素;如果没有这样的已排队线程,则没有可用于移除的元素并且 poll() 将会返回 null。对于其他 Collection 方法(例如 contains),SynchronousQueue 作为一个空 collection。此队列不允许 null 元素。
队列更多查看:http://blog.youkuaiyun.com/ghsau/article/details/8108292