package website.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池模拟
*
* @author lizixian
* @date 2021/6/3 10:30
*/
public class MyThreadPool {
private static ThreadPoolExecutor executor;
static {
executor = new ThreadPoolExecutor(4, 8,
100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2), new MyRejectPolicy());
}
// jdk 给出的几种拒绝handler
// 线程池对拒绝任务(无线程可用)的处理策略
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 用调用者所在的线程来执行任务(主线线程去执行当前任务,等待线程池有空闲继续执行)
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); // 直接抛出异常,这是默认策略
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); // 丢弃阻塞队列中靠最前的任务,并执行当前任务
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); // 直接丢弃任务
/**
* 自定义拒绝handler
*
* @author lizixian
* @date 2021/6/3 10:29
*/
static class MyRejectPolicy implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (r instanceof MyThread) {
MyThread myThread = (MyThread) r;
System.out.println("线程池拒绝了:" + myThread.getThreadName());
}
}
}
/**
* 自定义线程类
*
* @author lizixian
* @date 2021/6/3 10:28
*/
static class MyThread implements Runnable {
private String threadName;
MyThread(String threadName) {
this.threadName = threadName;
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
Thread.currentThread().setName(threadName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
for (int i = 0; i < 12; i++) {
executor.execute(new MyThread("我是第" + i + "个线程"));
}
}
}