1、程序入口:DabianTest
package com.lbh.myThreadPool.present; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class DabianTest { public static void main(String[] args) { //初始化池,并创建3条未执行任务的线程,这里new的是固定数量的线程,其他还有single,cached,schedule。 ExecutorService threadPool = Executors.newFixedThreadPool(2); System.out.println("初始化2个坑位"); //创建需要执行的线程任务,以对象数组的形式。 DabianThread[] dabianTh = new DabianThread[5]; dabianTh[0] = new DabianThread("张三"); dabianTh[1] = new DabianThread("李四"); dabianTh[2]= new DabianThread("王五"); dabianTh[3] = new DabianThread("郑六"); dabianTh[4] = new DabianThread("黄七"); System.out.println("所有人已准备就绪"); //执行任务(即添加到池中去,由池自动调度) for(int i = 0; i<dabianTh.length; i++){ threadPool.execute(dabianTh[i]); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } threadPool.shutdown();//设置执行完毕后自动关闭池 } }
2、工作线程类:DabianThread
package com.lbh.myThreadPool.present; /** * 被具象化的工作线程,比如此例子中可将此类认为是厕所 */ public class DabianThread implements Runnable { Dabian dabian; DabianThread(String name){ dabian = new DabianImpl(name); } public void run(){ dabian.process(); } }
3、业务实现类:DabianImpl
package com.lbh.myThreadPool.present; import java.text.SimpleDateFormat; import java.util.Date; public class DabianImpl implements Dabian { String humanName; SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss SS");// 设置日期格式 public DabianImpl(String humanName){ this.humanName = humanName; } @Override public void process() { System.out.println("当前:"+humanName+"开始大便。" + sdf.format(new Date())+"坑位号:"+Thread.currentThread().getId()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(humanName+"大便完成。" + sdf.format(new Date())+"坑位号:"+Thread.currentThread().getId()); } }
4、业务接口:Dabian
/** * */ package com.lbh.myThreadPool.present; /** * 大便接口,模拟多个需要大便的人,而床坑位只有有限的几个,因此采用线程池来控制需要坑位的使用。 *@comment *@author LolOT *@date 2015-3-6 下午4:31:42 *@version 1.0.0 *@see */ public interface Dabian { public void process(); }
DabianImpl