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包下面的日志打印
时间: 2024-10-10 08:45:22