📄 blockingqueuetest.java
字号:
/*
* BlockingQueueTest.java
*
* Created on 2007年9月14日, 下午1:10
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package product_consumer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
*
* @author Administrator
*/
public class BlockingQueueTest {
static BlockingQueue<String> basket;
public BlockingQueueTest() {
//定义了一个大小为2的BlockingQueue,也可根据需要用其他的具体类
basket = new ArrayBlockingQueue<String>(2);
}
class Producor implements Runnable {
public void run() {
while(true){
try {
//放入一个对象,若basket满了,等到basket有位置
basket.put("An apple");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
public void run() {
while(true){
try {
//取出一个对象,若basket为空,等到basket有东西为止
String result = basket.take();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public void execute(){
for(int i=0; i<10; i++){
new Thread(new Producor()).start();
new Thread(new Consumer()).start();
}
}
public static void main(String[] args){
BlockingQueueTest test = new BlockingQueueTest();
test.execute();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -