packagethreadpool_test;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingDeque;importjava.util.concurrent.TimeUnit;/*** 自定义一个简单的线程池
*
* ***/
public classThreadPool {private static final int coreThreadNum=3;//核心线程数
private static final int maxThreadNum=8;//最大线程数
private boolean working=true;//打开、关闭线程池
private BlockingQueue workThreads=new LinkedBlockingDeque<>(maxThreadNum);//当前工作线程
private BlockingQueue tasks=new LinkedBlockingDeque<>(10);//任务队列
public void execute(Runnable task) throwsInterruptedException{if(task==null) throw newNullPointerException();int workNum=workThreads.size();if(workNum
Worker worker=newWorker(task);
Thread thread=newThread(worker);
workThreads.offer(thread);//特殊值,add会抛出异常
thread.start();
}else if(tasks.size()<10){//任务池还没满,就把任务放进任务池里
tasks.offer(task);
}else if(workNum
Worker worker=newWorker();
Thread thread=newThread(worker);
System.out.println("开启新线程了"+thread.getName());
workThreads.offer(thread);
thread.start();
}else{
System.out.println("放弃该任务");return;
}
}public voidshutDown(){this.working=false;for(Thread worker:workThreads){
System.out.println("终止线程名:"+worker.getName());
worker.interrupt();
}
System.out.println("终止线程池线程");
Thread.currentThread().interrupt();
}private class Worker implements Runnable{//任务包装类
privateRunnable task_origal;publicWorker() {
}publicWorker(Runnable task) {this.task_origal=task;
}
@Overridepublic voidrun() {if(task_origal!=null)
task_origal.run();while(working){try{
Runnable task=tasks.take();//阻塞提取任务,阻塞状态下的中断并不会真的中断
task.run();
}catch(InterruptedException e) {
System.out.println("真的终止了");
Thread.currentThread().interrupt();
}
}
}
}
}