public class Task implements Runnable {
private int no;
private int size;
public Task(int no, int size) {
this.no = no;
this.size = size;
}
@Override
public void run() {
try {
System.out.println("执行中, Task: " + no + ", Thread: " + Thread.currentThread().getName() + ", queue.size: " + size);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
private static ExecutorService pool;
public static void main(String[] args) {
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(8);
pool = new ThreadPoolExecutor(
2,
5,
1000,
TimeUnit.MILLISECONDS,
queue,
Executors.defaultThreadFactory(),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("拒绝中, " + r.toString() + ", queue.size: " + queue.size());
}
});
for (int i = 0; i < 15; i++) {
pool.execute(new Task(i, queue.size()));
}
pool.shutdown();
}
}
执行中, Task: 1, Thread: pool-1-thread-2, queue.size: 0
执行中, Task: 10, Thread: pool-1-thread-3, queue.size: 8
执行中, Task: 11, Thread: pool-1-thread-4, queue.size: 8
执行中, Task: 12, Thread: pool-1-thread-5, queue.size: 8
执行中, Task: 0, Thread: pool-1-thread-1, queue.size: 0
拒绝中, com.example.demo.Task@6d6f6e28, queue.size: 8
拒绝中, com.example.demo.Task@135fbaa4, queue.size: 8
执行中, Task: 2, Thread: pool-1-thread-4, queue.size: 0
执行中, Task: 3, Thread: pool-1-thread-3, queue.size: 1
执行中, Task: 4, Thread: pool-1-thread-1, queue.size: 2
执行中, Task: 5, Thread: pool-1-thread-2, queue.size: 3
执行中, Task: 6, Thread: pool-1-thread-5, queue.size: 4
执行中, Task: 7, Thread: pool-1-thread-4, queue.size: 5
执行中, Task: 9, Thread: pool-1-thread-3, queue.size: 7
执行中, Task: 8, Thread: pool-1-thread-1, queue.size: 6
拒绝中, demo.Task@2d98a335, queue.size: 8
拒绝中, demo.Task@4e50df2e, queue.size: 8
执行中, Task: 11, Thread: pool-1-thread-4, queue.size: 8
执行中, Task: 10, Thread: pool-1-thread-3, queue.size: 8
执行中, Task: 12, Thread: pool-1-thread-5, queue.size: 8
执行中, Task: 0, Thread: pool-1-thread-1, queue.size: 0
执行中, Task: 1, Thread: pool-1-thread-2, queue.size: 0
执行中, Task: 3, Thread: pool-1-thread-4, queue.size: 1
执行中, Task: 2, Thread: pool-1-thread-3, queue.size: 0
执行中, Task: 4, Thread: pool-1-thread-5, queue.size: 2
执行中, Task: 5, Thread: pool-1-thread-2, queue.size: 3
执行中, Task: 6, Thread: pool-1-thread-1, queue.size: 4
执行中, Task: 7, Thread: pool-1-thread-4, queue.size: 5
执行中, Task: 8, Thread: pool-1-thread-3, queue.size: 6
执行中, Task: 9, Thread: pool-1-thread-2, queue.size: 7
可见 JDK17 的 ThreadPoolExecutor ,在通过 execut 提交 runnable 后,不会立即执行被提交的 runnable ,而是等待一段时间。如果在这段等待时间内没有新的 runnable 提交,才开始执行。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.