提供一个demo,仅供参考
public class ArrayBlockingQueueTestService {
// 自定义线程池
static ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(2000, 5000, 100, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1000));
// 元素队列
static ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(10);
// 计数器,模拟存入的元素
static AtomicInteger num = new AtomicInteger();
public static void main(String[] args) {
// 开启十个线程取元素
for (int i = 0; i < 1000; i++) {
threadPoolExecutor.execute(() -> {
try {
// 休眠200ms
Thread.sleep(200);
// 线程名称
String name = Thread.currentThread().getName();
// 取出元素
String take = arrayBlockingQueue.take();
System.out.println(name + "取出元素:" + take);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 开启十个线程存储元素
for (int i = 0; i < 1000; i++) {
threadPoolExecutor.execute(() -> {
try {
// 休眠200ms
Thread.sleep(200);
// 线程名称
String name = Thread.currentThread().getName();
// 计数器
int andIncrement = num.getAndIncrement();
// 写入队列
arrayBlockingQueue.put(String.valueOf(andIncrement));
System.out.println(name + "存入元素:" + andIncrement);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
threadPoolExecutor.shutdown();
}
}