package concurrent;
import java.util.concurrent.*;
public class C02_ExThreadpool {
public static class MyTask implements Runnable{
private String name;
public MyTask(String name){ this.name = name; }
public String getName() { return name; }
@Override
public void run() {
System.out.println(Thread.currentThread().getId() + ":" + name);
try{ Thread.sleep(1000);}
catch (InterruptedException e) { e.printStackTrace(); }
}
}
/**
* .通过自定义的线程工厂可以自定义线程的状态等信息
*/
public static class MyThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
// t.setDaemon(true); //设置为守护线程,主线程退出后自动销毁
System.out.println("create " + t);
return t;
}
}
public static void main(String[] args) throws InterruptedException{
/*
*.创建线程池,并重写线程池的beforeExecute、afterExecute、terminated。
*.这三个方法默认时空的,但我们可以重写去做一些事情
*/
ExecutorService es = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MICROSECONDS,
new LinkedBlockingDeque<>(), new MyThreadFactory()) {
@Override
protected void beforeExecute(Thread t, Runnable r) {
System.out.println("准备执行:" + ((MyTask)r).getName());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("执行完成:" + ((MyTask)r).getName());
}
@Override
protected void terminated() {
System.out.println("线程池退出");
}
};
//添加任务
for(int i=0 ; i<3 ; i++){
es.execute(new MyTask("Task-" + i));
Thread.sleep(10);
}
es.shutdown(); //发送一个信号给线程池,线程池在完成当前所有任务后关闭
}
}
console
create Thread[Thread-0,5,main]
准备执行:Task-0
11:Task-0
create Thread[Thread-1,5,main]
准备执行:Task-1
12:Task-1
create Thread[Thread-2,5,main]
准备执行:Task-2
13:Task-2
执行完成:Task-0
执行完成:Task-1
执行完成:Task-2
线程池退出