Java Concurrency - ThreadFactory, 使用工厂方法创建线程
当需要创建多个类似的线程实例时,使用工厂模式替代 new 操作符创建线程,能使代码更为简洁,易于维护。JDK 提供了 java.util.concurrent.ThreadFactory 接口,ThreadFactory 只有一个方法 newThread,它接收一个 Runnable 参数,返回一个 Thread 实例。
public class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable task) { Thread thread = new Thread(task); thread.setDaemon(true); return thread; } } public class Task implements Runnable { @Override public void run() { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { DaemonThreadFactory daemonThreadFactory = new DaemonThreadFactory(); for (int i = 0; i < 3; i++) { Thread thread = daemonThreadFactory.newThread(new Task()); thread.start(); } } }