用线程工厂创建线程
Posted 塑料味的美年达
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用线程工厂创建线程相关的知识,希望对你有一定的参考价值。
1.工厂模式/工厂
public class MyThreadFactory implements ThreadFactory {
private int counter;//线程数量
private String name;//线程名称
private List<String> stats;//线程对象信息
public MyThreadFactory(String name){
counter=0;
this.name=name;
stats=new ArrayList<String>();
}
//实例化thread对象
public Thread newThread(Runnable r) {
Thread t = new Thread(r,name+"_thread_"+counter);
counter++;
//保存线程创建时的信息
stats.add(String.format("created thread %d with name %s on %s\n",t.getId(),t.getName(),new Date()));
return t;
}
//返回stats集合信息
public String getStats(){
StringBuffer buffer=new StringBuffer();
Iterator<String> it=stats.iterator();
while (it.hasNext()) {
buffer.append(it.next());
buffer.append("\n");
}
return buffer.toString();
}
}
/**
* 线程
*/
public class Task implements Runnable{
Log log = LogFactory.getLog(this.getClass());
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
log.debug("thread sleep is not error");
} catch (InterruptedException e) {
e.printStackTrace();
log.debug("thread sleep is error in Task");
}
}
}
//调用
public class Main {
public static void main(String[] args){
//线程工厂
MyThreadFactory factory = new MyThreadFactory("MyThreadFactory");
//新线程
Task task = new Task();
Thread thread;
System.out.println("Start the threads\n");
for(int i=0;i<10;i++){
thread=factory.newThread(task);
thread.start();
System.out.printf("Factory stats:\n"); System.out.printf("%s\n",factory.getStats());
}
}
}
//顺带说下日记
Log log = LogFactory.getLog(this.getClass());
log.dubug(");
这个是common.logging包下面的日志打印
以上是关于用线程工厂创建线程的主要内容,如果未能解决你的问题,请参考以下文章
newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段