package testForFun.demo20181210.demo02;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created with IntelliJ IDEA
* User:Ryannn
* Date:2018/12/13
* Time:19:06
*/
public class Test03 {
class WorkThread extends Thread{
private Runnable target;
private AtomicInteger counter;
public WorkThread(ThreadGroup group, String name, Runnable target, AtomicInteger counter) {
super(group, name);
this.target = target;
this.counter = counter;
}
@Override
public void run() {
try {
target.run();
}finally {
int c = counter.getAndDecrement();
System.out.println("terminate no " + c + " Threads");
}
}
}
static class WorkRunnable implements Runnable{
/**
*
* @see Thread#run()
*/
@Override
public void run() {
System.out.println("Comoplete a task");
}
}
/*
线程工场
*/
static class WorkThreadFactory implements ThreadFactory{
private AtomicInteger atomicInteger =new AtomicInteger(0);
/**
* Constructs a new {@code Thread}. Implementations may also initialize
* priority, name, daemon status, {@code ThreadGroup}, etc.
*
* @param r a runnable to be executed by new thread instance
* @return constructed thread, or {@code null} if the request to
* create a thread is rejected
*/
@Override
public Thread newThread(Runnable r) {
int c = atomicInteger.incrementAndGet();
System.out.println("create no " + c + " Threads");
return new Thread(r, String.valueOf(atomicInteger));
}
}
public static void main(String[] args){
ExecutorService es = Executors.newCachedThreadPool(new WorkThreadFactory());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
//指示当所有线程执行完毕后关闭线程池和工作线程,如果不调用此方法,jvm不会自动关闭
es.shutdown();
try {
//阻止所有任务在关闭请求完成后执行,或发生超时,或当前线程中断,以先到者为准。
es.awaitTermination(2*60,TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
接口:ThreadFactory
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Set对每个对象只接受一次,并使用自己内部的排序方法(通常,你只关心某个元素是否属于Set,而不关心它的顺序--否...
- EhsanTang/ApiManager: ApiManager - CrapApi免费开源API接口管理系统、A...
- 相关函数接口信息 : 示例程序 : 1.if_name_index.c 示例: 编译并运行 : 2.if_inde...
- 抓取手机网络包 使用场景:测试手机app时,功能出现异常,通常就需要通过截取网络封包来分析、定位问题 前提:手机和...