码迷,mamicode.com
首页 > 编程语言 > 详细

用线程工厂创建线程

时间:2017-11-25 16:23:50      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:log   iterator   debug   star   counter   gets   stringbu   print   count   

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包下面的日志打印

用线程工厂创建线程

标签:log   iterator   debug   star   counter   gets   stringbu   print   count   

原文地址:http://www.cnblogs.com/yxb-ylp-520/p/7895312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!