- 先上代码
public class BlockingQueueTest {
private static ArrayBlockingQueue<String> QUEUE = new ArrayBlockingQueue<String>(
100, true);
public static void main(String[] args) {
Random random1 = new Random(100);
Thread t1 = new Thread(() -> {
while (true) {
String a = random1.nextInt() + "";
try {
QUEUE.put(a);
System.err.println("入列:" + a);
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
Thread t2 = new Thread(() -> {
while (true) {
try {
String a = QUEUE.take().toString();
System.err.println("出列:" + a);
System.err.println("队列大小:" + QUEUE.size());
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
t1.start();
t2.start();
}
}
- BlockingQueue接口中的方法