线程池简单实现java_简单实现java线程池
package?com.ty.thread;
importjava.util.HashSet;importjava.util.Set;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingQueue;/***@authorTaoyong
* @date 2018年5月17日
* 天下沒有難敲的代碼!*/
public classThreadPoolExecutor {//維護線程的list
private Set threadList = new HashSet();/** 阻塞隊列是線程安全的,主要使用在生產/消費者的場景*/
private BlockingQueueblockingQueue;//線程池的工作線程數
private int poolSize = 0;//線程池的核心容量
private int coreSize = 0;private boolean shutDown = false;public ThreadPoolExecutor(intsize) {this.poolSize =size;
blockingQueue= new LinkedBlockingQueue<>(poolSize);
}public void execute(Task task) throwsInterruptedException {if(shutDown == true) {return;
}if(coreSize
blockingQueue.offer(task);
produceWorker(task);
}else{
blockingQueue.put(task);
}
}private void produceWorker(Task task) throwsInterruptedException {if(task == null) {throw new NullPointerException("非法參數:傳入的task對象為空!");
}if(shutDown == true) {return;
}
Thread thread= new Thread(newWorker());
threadList.add(thread);
coreSize++;
thread.start();
}public voidshutDown() {if(threadList == null || threadList.size() == 0) {return;
}
shutDown= true;for(Thread thread: threadList) {
System.out.println(thread.getName()+ " interrupt");
thread.interrupt();
}
}/** 此內部類是實際上的工作線?worker是實現了Runnable接口的實際工作線程,通過while(true)循環從BlockingQueue中取任務執行。
**/
class Worker implementsRunnable {
@Overridepublic voidrun() {while(true && shutDown == false) {try{
blockingQueue.take().doJob();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
總結
以上是生活随笔為你收集整理的线程池简单实现java_简单实现java线程池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人民币对美元升值8%,为什么人民币升值这
- 下一篇: 【LeetCode - 798】得分最高