用线程工厂创建线程

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包下面的日志打印
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值