package com.xt.thinks21_2; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; /**
* 后台线程工厂测试
*
* @step 1
* @author Administrator
*
*/
class DaemonThreadFactory implements ThreadFactory { @Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r);
t.setDaemon(true);
return t;
} } /**
* 自定义线程池执行器
*
* @step 5
* @author Administrator
*
*/
class DaemonThreadPoolExecutor extends ThreadPoolExecutor { public DaemonThreadPoolExecutor() {
super(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), new DaemonThreadFactory());
// TODO Auto-generated constructor stub
} } /**
* 后台线程测试
*
* @step 2
* @author Administrator
*
*/
public class DaemonFromFactory implements Runnable {
// @step 3
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + ":" + this);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public static void main(String[] args) {
// @step 4
ExecutorService es = Executors
.newCachedThreadPool(new DaemonThreadFactory());
for (int i = 0; i < 10; i++) {
es.execute(new DaemonFromFactory());// 执行后台线程
}
es.shutdown();
// @step 6
// 自定义的线程池执行器
DaemonThreadPoolExecutor dte = new DaemonThreadPoolExecutor();
for (int i = 0; i < 10; i++) {
dte.execute(new DaemonFromFactory());// 执行后台线程
}
dte.shutdown();
System.out.println("ALL DEAMON THREAD IS START!");
try {
TimeUnit.MILLISECONDS.sleep(125);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
通过编写定制的ThreadFactory可以定制游Executor创建的线程的属性(后台、优先级、名称)