ThreadPoolExecutor是常用的java线程池实现,之前的项目中也一直有用到,本文记录两个基本的例子和参数设置。
例子1:
public class Thread1 { public void ThreadOperation(){ BlockingQueue queue = new LinkedBlockingQueue(); ThreadPoolExecutor executer = new ThreadPoolExecutor(3,6,1,TimeUnit.DAYS,queue); for(int i = 0; i < 10; i++){ executer.execute(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("execute:"); } }); executer.shutdown(); } }
例子2:
public class Thread2 { class MyFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { // TODO Auto-generated method stub System.out.println("newThread"); Thread t = new Thread(r); t.setName("Fredric"); return t; } } public void ThreadOperation(){ BlockingQueue queue = new LinkedBlockingQueue(4);//特地限制了缓存队列的大小 ThreadPoolExecutor executor = new ThreadPoolExecutor(3,//初始线程数 6,//当缓存满时创建的最大线程数 100,//多余线程等待任务的时间 TimeUnit.MILLISECONDS,//时间的单位 queue, new MyFactory()); for(int i = 0; i < 10; i++){ executor.execute(new Runnable(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("executer"+ Thread.currentThread().getName()); } }); } try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } for(int i = 0; i < 5; i++){ executor.execute(new Runnable(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("executer "+" next "+ Thread.currentThread().getName()); } }); } executor.shutdown(); } }
第二个例子证明参数的使用,其打印如下:
newThread
newThread
newThread //系统启动时的核心线程 3个
newThread
newThread
newThread //当缓存队列满时,增加线程至 10个
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
executerFredric
newThread
newThread
newThread //超时后,新增的3个线程被销毁,因此被重新创建
executer next Fredric
executer next Fredric
executer next Fredric
executer next Fredric
executer next Fredric