1.AbortPolicy:拋出異常
throws a {@code RejectedExecutionException}.
private static void testAbortPolicy() throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),
r -> {
Thread thread = new Thread(r);
return thread;
}, new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 3; i++) {
executor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
TimeUnit.SECONDS.sleep(1);
executor.execute(() -> {
System.out.println("Can this task execute???");
});
}

拒絕策略1.png
2.DiscardPolicy: 拒絕任務(wù)
silently discards the rejected task.
private static void testDiscardPolicy() throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),
r -> {
Thread thread = new Thread(r);
return thread;
}, new ThreadPoolExecutor.DiscardPolicy());
for (int i = 0; i < 3; i++) {
executor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
TimeUnit.SECONDS.sleep(1);
executor.execute(() -> {
System.out.println("Can this task execute???");
});
}

拒絕策略2ng
3.CallerRunsPolicy:直接使用調(diào)用線程執(zhí)行任務(wù)
runs the rejected task directly in the calling thread of the {@code execute} method,unless the executor has been shut down, in which case the task is discarded.
private static void testCallerRunsPolicy() throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),
r -> {
Thread thread = new Thread(r);
return thread;
}, new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 3; i++) {
executor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
TimeUnit.SECONDS.sleep(1);
executor.execute(() -> {
System.out.println("Can this task execute??? Yes, is execute in thread " + Thread.currentThread().getName());
});
}

拒絕策略3.png
4.DiscardOldestPolicy:拋棄隊列中的未執(zhí)行的任務(wù),嘗試重新執(zhí)行
discards the oldest unhandled request and then retries {@code execute},unless the executor is shut down, in which case the task is discarded.
private static void testDiscardOldestPolicy() throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),
r -> {
Thread thread = new Thread(r);
return thread;
}, new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 0; i < 3; i++) {
executor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println("I am from lambda.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
TimeUnit.SECONDS.sleep(1);
executor.execute(() -> {
System.out.println("Can this task execute??? Yes, is execute in thread " + Thread.currentThread().getName());
});
}

拒絕策略4.png