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();
}
}