实现说明
整个示例围绕类 RejectPolicyDemo和函数 main、runWith、sleep组织。
for (int i = 1; i <= 3; i++) 反复执行,循环体之外没有别的重复。
使用要点
- 执行文件,
main会按顺序走完runWith、sleep。
常见问题
「Executor 饱和拒绝策略」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
核心语句
Thread.currentThread().interrupt();
Thread.sleep(ms);
runWith("caller-runs", new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.CallerRunsPolicy()));
代码示例
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class RejectPolicyDemo {
public static void main(String[] args) {
// 单线程 + SynchronousQueue:worker 一忙,新任务立刻被拒,策略完全可控
runWith("abort", new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.AbortPolicy()));
runWith("caller-runs", new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.CallerRunsPolicy()));
}
static void runWith(String label, ThreadPoolExecutor pool) {
AtomicInteger executed = new AtomicInteger();
for (int i = 1; i <= 3; i++) {
try {
pool.execute(() -> {
sleep(200); // 占住 worker,制造后续任务被拒的窗口
executed.incrementAndGet();
});
} catch (RejectedExecutionException e) {
System.out.println(label + ": task " + i + " rejected");
}
}
pool.shutdown();
try {
pool.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(label + ": executed = " + executed.get());
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}