import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* TODO 在此写上类的相关说明.<br>
* @author gongqiang <br>
* @version 1.0.0 2021年6月2日<br>
* @see
* @since JDK 1.5.0
*/
public class BlockingQueueDemo {
/**
* @param args
*/
public static void main(String[] args) {
final BlockingQueue<Integer> blockQueue = new LinkedBlockingQueue<>(10);
new Thread(() -> {
while (true) {
try {
final Integer value = new Random().nextInt();
final boolean success = blockQueue.offer(value);
if (success) {
System.out.println("向阻塞队列添加" + value + "成功。");
}
Thread.sleep(7000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
new Thread(() -> {
while (true) {
try {
final Integer value = blockQueue.take();
System.out.println("从阻塞队列获取" + value + "成功。");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
try {
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}