标签:style io ar os 使用 sp for on 数据
工厂模式是我们常用的模式之一。它是一个创建者模式,使用一个类为其他的或者多个类创建对象。当我们要为这些类创建对象时,不需要在使用new构造器。
使用工厂类,可以将对象的创建集中化。
下面这个例子,我们使用ThreadFactory接口来创建对象,用来生成个性化名称的线程并且保存这些线程对象的统计信息。
1.创建名为MyThreadFactory的类,并且实现ThreadFactory接口。
public class MyThreadFactory implements ThreadFactory{public class MyThreadFactory implements ThreadFactory}
2.声明三个属性。整型数字counter,用来存储线程对象的数量;字符串name,用来存放每个线程名称;字符串列表stats,用来存放线程对象的统计数据。同时实现带参数的构造器初始化这3个属性。
private int counter;
private String name;
private List<String>stats;
public MyThreadFactory(String name) {
counter=0;
this.name = name;
stats=new ArrayList<String>();
}
3.实现newThread()方法。这个方法以Runnable接口对象为参数。并且返回参数对应的线程对象。我们创建一个线程并且生成线程名称,保存统计数据。
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;
}
4.实现getStas()方法,返回一个字符串对象。用来表示所有线程对象的统计数据。
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();
}
5.创建名为Task的类并且实现Runnable接口。我们这里,线程除了只休眠1秒,,不做任何事情。
public class Task implements Runnable{
public void run(){
try{
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
6.创建主类Main,包含main()方法。
public class Main {
public static void main(String[] args){}}
7.创建一个MyThreadFactory对象,创建一个Task对象。
MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
Task task=new Task();
8.使用工厂类MyThreadFactory创建10个对象线程,并且启动。
Thread thread;
System.out.printf("Starting 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());
}
10.运行结果。
Starting the Threads
Factory stats:
Created thread 9 with name MyThreadFactory-Thread_0 on Thu Dec 11 21:02:42 CST 2014
Created thread 10 with name MyThreadFactory-Thread_1 on Thu Dec 11 21:02:42 CST 2014
Created thread 11 with name MyThreadFactory-Thread_2 on Thu Dec 11 21:02:42 CST 2014
Created thread 12 with name MyThreadFactory-Thread_3 on Thu Dec 11 21:02:42 CST 2014
Created thread 13 with name MyThreadFactory-Thread_4 on Thu Dec 11 21:02:42 CST 2014
Created thread 14 with name MyThreadFactory-Thread_5 on Thu Dec 11 21:02:42 CST 2014
Created thread 15 with name MyThreadFactory-Thread_6 on Thu Dec 11 21:02:42 CST 2014
Created thread 16 with name MyThreadFactory-Thread_7 on Thu Dec 11 21:02:42 CST 2014
Created thread 17 with name MyThreadFactory-Thread_8 on Thu Dec 11 21:02:42 CST 2014
Created thread 18 with name MyThreadFactory-Thread_9 on Thu Dec 11 21:02:42 CST 2014
标签:style io ar os 使用 sp for on 数据
原文地址:http://www.cnblogs.com/wanming88/p/4158496.html