本文到实例中将讲解一下如何使用ThreadFactory
接口。这个接口是Java自身提供的,用户可以实现它自定义自己的线程启动方式,可以设置线程名称、类型以及优先级等属性。
ThreadFactory
vs Default ThreadFactory
:
在一个典型的Java ExecutorService程序中,其线程都需要被指定以何种形式运行,如果程序初始化ExecutorService
时没有指定ThreadFactory
,程序会采用一个默认的ThreadFactory
来生成提交线程,但是对于一个严谨对程序来说,定义自己的ThreadFactory
永远是个最佳选择。Why??
- 设置更有描述意义的线程名称。如果使用默认的
ThreadFactory
,它给线程起名字大概规律就是pool-m-thread-n这个样子,如pool-1-thread-1。但是当你分析一个thread dump时,看着这样的名字就很难知道线程的目的。所以使用一个有描述意义的线程名称是分析追踪问题的clue NO.1。 - 设置线程是否是守护线程,默认的
ThreadFactory
总是提交非守护线程 - 设置线程优先级,默认
ThreadFactory
总是提交的一般优先级线程
例子:
CustomThreadFactoryBuilder
类实现了一种优雅的Builder Mechanism
方式去得到一个自定义ThreadFactory
实例。ThreadFactory
接口中有一个接受Runnable
类型参数的方法newThread(Runnable r)
,你自己的factory逻辑就应该写在这个方法中,去配置线程名称、优先级、守护线程状态等属性。
public class CustomThreadFactoryBuilder {
private String namePrefix = null;
private boolean daemon = false;
private int priority = Thread.NORM_PRIORITY;
public CustomThreadFactoryBuilder setNamePrefix(String namePrefix) {
if (namePrefix == null) {
throw new NullPointerException();
}
this.namePrefix = namePrefix;
return this;
}
public CustomThreadFactoryBuilder setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
public CustomThreadFactoryBuilder setPriority(int priority) {
if (priority < Thread.MIN_PRIORITY){
throw new IllegalArgumentException(String.format(
"Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY));
}
if (priority > Thread.MAX_PRIORITY) {
throw new IllegalArgumentException(String.format(
"Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY));
}
this.priority = priority;
return this;
}
public ThreadFactory build() {
return build(this);
}
private static ThreadFactory build(CustomThreadFactoryBuilder builder) {
final String namePrefix = builder.namePrefix;
final Boolean daemon = builder.daemon;
final Integer priority = builder.priority;
final AtomicLong count = new AtomicLong(0);
/*
return new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
if (namePrefix != null) {
thread.setName(namePrefix + "-" + count.getAndIncrement());
}
if (daemon != null) {
thread.setDaemon(daemon);
}
if (priority != null) {
thread.setPriority(priority);
}
return thread;
}
};*/
//jdk8中还是优先使用lamb表达式
return (Runnable runnable) -> {
Thread thread = new Thread(runnable);
if (namePrefix != null) {
thread.setName(namePrefix + "-" + count.getAndIncrement());
}
if (daemon != null) {
thread.setDaemon(daemon);
}
/*
thread.setPriority(priority);
*/
return thread;
};
}
}
SimpleTask
类实现类Runnable接口,打印出了线程的运行属性(名称,优先级等)。
public class SimpleTask implements Runnable {
private long sleepTime;
public SimpleTask(long sleepTime) {
super();
this.sleepTime = sleepTime;
}
@Override
public void run() {
while (true) {
try {
System.out.println("Simple task is running on "
+ Thread.currentThread().getName() + " with priority " + Thread.currentThread().getPriority());
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
CustomThreadFactoryDemo
类使用我们上面的CustomThreadFactoryBuilder
类创建类一个ThreadFactory
实例,又使用这个实例获得类一个ExecutoryService
,这样所有这个线程池中的线程都会按我们定义好的属性被生成,下面代码中执行类三个SimpleTask。
public class CustomThreadFactoryDemo {
public static void main(String[] args) {
ThreadFactory customThreadfactory = new CustomThreadFactoryBuilder()
.setNamePrefix("DemoPool-Thread").setDaemon(false)
.setPriority(Thread.MAX_PRIORITY).build();
ExecutorService executorService = Executors.newFixedThreadPool(3,
customThreadfactory);
// Create three simple tasks with 1000 ms sleep time
SimpleTask simpleTask1 = new SimpleTask(1000);
SimpleTask simpleTask2 = new SimpleTask(1000);
SimpleTask simpleTask3 = new SimpleTask(1000);
// Execute three simple tasks with 1000 ms sleep time
executorService.execute(simpleTask1);
executorService.execute(simpleTask2);
executorService.execute(simpleTask3);
}
}
输出:
Simple task is running on DemoPool-Thread-0 with priority 10
Simple task is running on DemoPool-Thread-1 with priority 10
Simple task is running on DemoPool-Thread-2 with priority 10
Simple task is running on DemoPool-Thread-0 with priority 10
Simple task is running on DemoPool-Thread-1 with priority 10
Simple task is running on DemoPool-Thread-2 with priority 10
Simple task is running on DemoPool-Thread-0 with priority 10
Simple task is running on DemoPool-Thread-1 with priority 10
Simple task is running on DemoPool-Thread-2 with priority 10
Simple task is running on DemoPool-Thread-0 with priority 10
Simple task is running on DemoPool-Thread-1 with priority 10
Simple task is running on DemoPool-Thread-2 with priority 10