1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.SynchronousQueue; 6 import java.util.concurrent.ThreadFactory; 7 import java.util.concurrent.ThreadPoolExecutor; 8 import java.util.concurrent.TimeUnit; 9 10 /**11 * 后台线程工厂测试12 * 13 * @step 114 * @author Administrator15 *16 */17 class DaemonThreadFactory implements ThreadFactory {18 19 @Override20 public Thread newThread(Runnable r) {21 // TODO Auto-generated method stub22 Thread t = new Thread(r);23 t.setDaemon(true);24 return t;25 }26 27 }28 29 /**30 * 自定义线程池执行器31 * 32 * @step 533 * @author Administrator34 *35 */36 class DaemonThreadPoolExecutor extends ThreadPoolExecutor {37 38 public DaemonThreadPoolExecutor() {39 super(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,40 new SynchronousQueue(), new DaemonThreadFactory());41 // TODO Auto-generated constructor stub42 }43 44 }45 46 /**47 * 后台线程测试48 * 49 * @step 250 * @author Administrator51 *52 */53 public class DaemonFromFactory implements Runnable {54 // @step 355 @Override56 public void run() {57 // TODO Auto-generated method stub58 while (true) {59 try {60 TimeUnit.MILLISECONDS.sleep(100);61 System.out.println(Thread.currentThread() + ":" + this);62 } catch (InterruptedException e) {63 // TODO Auto-generated catch block64 e.printStackTrace();65 }66 }67 }68 69 public static void main(String[] args) {70 // @step 471 ExecutorService es = Executors72 .newCachedThreadPool(new DaemonThreadFactory());73 for (int i = 0; i < 10; i++) {74 es.execute(new DaemonFromFactory());// 执行后台线程75 }76 es.shutdown();77 // @step 678 // 自定义的线程池执行器79 DaemonThreadPoolExecutor dte = new DaemonThreadPoolExecutor();80 for (int i = 0; i < 10; i++) {81 dte.execute(new DaemonFromFactory());// 执行后台线程82 }83 dte.shutdown();84 System.out.println("ALL DEAMON THREAD IS START!");85 try {86 TimeUnit.MILLISECONDS.sleep(125);87 } catch (InterruptedException e) {88 // TODO Auto-generated catch block89 e.printStackTrace();90 }91 }92 }
通过编写定制的ThreadFactory可以定制游Executor创建的线程的属性(后台、优先级、名称)