package concurrent.policy;
/**
* @className: MyThread
* @description: 线程类
* @date: 2022/5/8
* @author: cakin
*/
public class MyThread implements Runnable {
private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
try {
System.out.println("threadName :" + this.threadName);
System.out.println(threadName + "执行了 1 秒钟...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
}
package concurrent.policy;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @className: MyRejectPolicy
* @description: 自定义拒绝策略
* @date: 2022/5/8
* @author: cakin
*/
public class MyRejectPolicy implements RejectedExecutionHandler {
public MyRejectPolicy() {
}
// 自定义拒绝方法
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("被拒绝的线程名:" + ((MyThread) r).getThreadName());
}
}
package concurrent.policy;
import java.util.concurrent.*;
/**
* @className: TestMyThreadPool
* @description: 线程池测试类
* @date: 2022/5/8
* @author: cakin
*/
public class TestMyThreadPool {
public static void main(String[] args) {
/*
核心线程:1,如果只有1个任务,会直接交给线程池中的这一个线程来处理
最大线程数:2,如果任务的数量>核心线程数1+workQueue.size(),且任务的数量<=大线程数2+workQueue.size()之和时,就将新提交的任务交给非核心线程处理
最大空闲时间:10秒
任务队列:有界队列ArrayBlockingQueue,该队列中可以存放3个任务
拒绝策略:AbortPolicy(), 当提交任务数>最大线程数2+workQueue.size()之和时,任务会交给AbortPolicy()来处理
*/
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS,
//new PriorityBlockingQueue<Runnable>(),
new ArrayBlockingQueue<Runnable>(3),
new MyRejectPolicy()
//new ThreadPoolExecutor.AbortPolicy()
);
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
MyThread t3 = new MyThread("t3");
MyThread t4 = new MyThread("t4");
MyThread t5 = new MyThread("t5");
MyThread t6 = new MyThread("t6");
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.shutdown();
}
}
被拒绝的线程名:t6
threadName :t5
threadName :t1
t5执行了 1 秒钟...
t1执行了 1 秒钟...
threadName :t2
threadName :t3
t3执行了 1 秒钟...
t2执行了 1 秒钟...
threadName :t4
t4执行了 1 秒钟...
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/124653511
内容来源于网络,如有侵权,请联系作者删除!