线程池的手写和拒绝策略

手写线程池:

AbortPolicy:直接抛出RejectedExecutionException异常阻止系统正常运行。

public class MyThreadPoolDemo {
public static void main(String[ ]args) {
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
        //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
        for(int i =1; i <= 10; i++) {
threadPool.execute(() ->{
System.out.println(Thread.currentThread().getName()+"\t 办理业务");
});
}
}
}

运行结果见下图,抛异常,因为最大线程数5加上阻塞队列3最多可以容纳8个,超过8个就会抛异常


CallerRunsPolicy: "调用者运行"一种调节机制,该策略即不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量。
public class MyThreadPoolDemo {
public static void main(String[ ]args) {
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
for(int i =1; i <= 10; i++) {
threadPool.execute(() ->{
System.out.println(Thread.currentThread().getName()+"\t 办理业务");
});
}
}
}

运行结果见下图:


DiscardOldestPolicy:抛弃队列中等待最近的任务,然后把当前任务加入队列中尝试再次提交当前任务
public class MyThreadPoolDemo {
public static void main(String[ ]args) {
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
for(int i =1; i <= 10; i++) {
threadPool.execute(() ->{
System.out.println(Thread.currentThread().getName()+"\t 办理业务");
});
}
}
}

运行结果见下图:


DiscardPolicy:直接丢弃任务,不予任何处理也不抛出异常,如果允许任务丢失,这是最好的一种方案。
public class MyThreadPoolDemo {
public static void main(String[ ]args) {
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
for(int i =1; i <= 10; i++) {
threadPool.execute(() ->{
System.out.println(Thread.currentThread().getName()+"\t 办理业务");
});
}
}
}

运行结果见下图:



猜你喜欢

转载自www.cnblogs.com/liuyi13535496566/p/12168586.html