package concurrentTest;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TestBlockingQueue {
public static void main(String[] args) {
final BlockingQueue<Integer> queue=new LinkedBlockingQueue<Integer>(3);
final Random random=new Random();
class Producer implements Runnable{
public void run() {
while(true){
try {
int i=random.nextInt(100);
queue.put(i);//當隊列達到容量時候,會自動阻塞的
System.out.println("put "+ i + " into queue");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
public void run() {
while(true){
try {
System.out.println("consumer:" + queue.take());//當隊列爲空時,也會自動阻塞
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}
BlockingQueue
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.