import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQuenceTest {
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(10);
public void put() {
try {
blockingQueue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public BlockingQueue<Integer> getBlockingQueue() {
return blockingQueue;
}
public static void main(String[] args) {
BlockingQuenceTest b = new BlockingQuenceTest();
TheadTest tt = new TheadTest(b);
for (int i = 0; i < 20; i++) {
new Thread(tt).start();
}
BlockingQueue<Integer> blockingQueue = b.getBlockingQueue();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
int size = blockingQueue.size();
System.out.println("之前:" + size);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
blockingQueue.clear();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
size = blockingQueue.size();
System.out.println("之后:" + size);
}
}
class TheadTest implements Runnable {
private BlockingQuenceTest blockingQueue;
public TheadTest(BlockingQuenceTest blockingQueue) {
this.blockingQueue = blockingQueue;
}
public void run() {
blockingQueue.put();
}
}
多线程 - 阻塞队列blockingQueue用法
最新推荐文章于 2024-07-29 21:55:07 发布