700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 线程池简单实现java_简单实现java线程池

线程池简单实现java_简单实现java线程池

时间:2020-05-08 11:08:09

相关推荐

线程池简单实现java_简单实现java线程池

packagecom.ty.thread;

importjava.util.HashSet;importjava.util.Set;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingQueue;/***@authorTaoyong

* @date 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();

}

}

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。