package com.tij.chapter1;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
*
* @author Allen
* @date 2017-8-7
*
*/
class DaemonThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}
class DaemonFromFactory implements Runnable {
private String threadName;
private CountDownLatch latch;
public DaemonFromFactory(int i, CountDownLatch latch) {
this.threadName = "thread-" + i;
this.latch = latch;
}
@Override
public void run() {
while (true) {
try {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + "--" + this);
System.out.println("count--" + latch.getCount());
} catch (Exception e) {
e.printStackTrace();
}finally{
latch.countDown();
}
}
}
@Override
public String toString() {
return threadName;
}
}
public class DaemonTest {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(10);
ExecutorService exec = Executors
.newCachedThreadPool(new DaemonThreadFactory());
for (int i = 0; i < 10; i++) {
exec.execute(new DaemonFromFactory(i, latch));
}
System.out.println("All Threads Start");
try {
//latch.await(500, TimeUnit.MILLISECONDS);
latch.await();
//Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//主线程完成,则后台线程也全部中断
System.out.println("Task Stopped");
}
}
后台线程的finally语句不会执行,因为父线程即main线程执行结束后,jvm会关闭所有线程,可以通过Executor来实现有序的关闭线程