import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
public class MyBlockingQueue implements Runnable {
BlockingQueue<String> queue;
private int index;
public MyBlockingQueue(BlockingQueue<String> queue, int index) {
this.queue = queue;
this.index = index;
}
@Override
public void run() {
try {
queue.put(String.valueOf(this.index));
System.out.println("{" + this.index + "} in queue!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(3);
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("aaa-%s").build();
ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024), factory, new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 10; i++) {
pool.submit(new MyBlockingQueue(queue, i));
}
//为什么这里的线程不执行呢?
pool.submit(() -> {
try {
while (true) {
System.out.println("=======" + queue.size());
if (queue.isEmpty()) {
break;
}
String str = queue.take();
System.out.println(str + " has take!");
}
} catch (Exception e) {
e.printStackTrace();
}
});
pool.shutdown();
}
}
首先想说一下,其中的问题,阻塞队列和工厂模式OK,
在创建线程池的时候并不建议使用ExecutorService 中的构造函数,而是使用Executors里面提供的四种静态方法,很多的参数配置已经写好。
其次,给线程池submit的应该是线程,而不是阻塞队列,你那里submit的是阻塞队列噢,循环体里面你可以写一个自己的类
比如(class MyThread extends Thread),再写一个print,sleep一下,就可以看到线程池的执行啦。
https://blog.csdn.net/whandwho/article/details/82931798 这个博客下方第八点