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();
}
/**
* 總結:上面的代碼沒有原子性,打印的結果可能會出現偏差
*/
}
ArrayBlockingQueue
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.