通过工厂方法创建线程
工厂方法设计模式是面向对象编程中最常用的设计模式之一,工厂方法属于创建类型,主要用来创建对象;
使用工厂方法创建对象有几个有点:
- 很容易改变创建的对象或者创建对象的方法;
- 限制创建对象的数量;
- 很容易的对这些创建的对象进行数据统计(generate statistic data)
Java提供了ThreadFactory 接口用来实现工厂方法创建线程;
动手实现
1.实现一个工厂方法
public class MyThreadFactory implements ThreadFactory {
private AtomicInteger threadNumber = new AtomicInteger(0);
// Store thread name
private String name;
// Store statistical data about the Thread object created
private List<String> stats;
private ThreadGroup group;
public MyThreadFactory(String name) {
this.name = name;
stats = new ArrayList<>();
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group,r, name + "-Thread_" + threadNumber.getAndIncrement());
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
stats.add(String.format("Created thread %d with name %s in group %s, on %s\n", t.getId(), t.getName(),t.getThreadGroup().getName(), Utils.dateFormat(new Date())));
return t;
}
public String getStats() {
StringBuffer buffer = new StringBuffer();
for (String stat : stats) {
buffer.append(stat);
buffer.append("\n");
}
return buffer.toString();
}
}
2.实现一个线程任务
public class Task implements Runnable {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyThreadFactory threadFactory = new MyThreadFactory("MyThreadFactory");
Task task=new Task();
Thread thread;
System.out.printf("Starting the Threads\n");
for (int i=0; i<10; i++){
thread=threadFactory.newThread(task);
thread.start();
}
System.out.printf("Factory stats:\n");
System.out.printf("%s\n",threadFactory.getStats());
}
}
stats中保存了创建这些对象的信息,可以作为一个统计结果
要点
ThreadFactory 接口提供了newThread方法,用来创建线程,在这个方法里,对于创建的线程我们可以加入一些更多的控制;工厂方法和静态工厂方法是不一样的,具体区别以后记录;