Java ThreadFactory接口用法

根据需要创建新线程的对象。使用线程工厂就无需再手工编写对 new Thread 的调用了,从而允许应用程序使用特殊的线程子类、属性等等。

JDK中的介绍:

An object that creates new threads on demand. Using thread factories removes hardwiring of calls tonew Thread, enabling applications to use special thread subclasses, priorities, etc.

The simplest implementation of this interface is just:

 class SimpleThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
     return new Thread(r);
   }
 }

The Executors.defaultThreadFactory method provides a more useful simple implementation, that sets the created thread context to known values before returning it. 

/**
     * The default thread factory
     */
    static class DefaultThreadFactory implements ThreadFactory {
        static final AtomicInteger poolNumber = new AtomicInteger(1);
        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null)? s.getThreadGroup() :
                                 Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

下面写一简单示例。
package com.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class Task implements Runnable{
	int taskId;
	public Task(int taskId) {
		this.taskId=taskId;
	}
	
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()+"--taskId: "+taskId);
		
	}
}

class DaemonThreadFactory implements ThreadFactory {
	@Override
	public Thread newThread(Runnable r) {
		Thread t=new Thread(r);
		t.setDaemon(true);
		return t;
	}
	
}
public class ThreadFactoryTest {
	public static void main(String[] args) {
		ExecutorService exec=Executors.newFixedThreadPool(3,new DaemonThreadFactory());
		for(int i=0;i<3;i++) {
			exec.submit(new Task(i));
		}
		exec.shutdown();
	}
}

输出如下:

Thread-0--taskId: 0
Thread-1--taskId: 1
Thread-2--taskId: 2

分析:
DaemonThreadFactory中覆写的newThread()方法与submit()方法的调用关系,也就是说 DaemonThreadFactory是如何起作用的。
调试输出其调用关系:


也就是说,submit()时会调用DaemonThreadFactory类的newThread()方法来创建线程。

ThreadPoolExecutor的ThreadFactory是用于创建线程的工厂类。它定义了如何创建新的线程对象,并且可以自定义线程的属性和行为。 要使用ThreadFactory,需要实现ThreadFactory接口,并重写其中的newThread方法newThread方法接收一个Runnable对象作为参数,并返回一个新创建的Thread对象。 下面是一个示例代码,演示如何使用ThreadFactory创建线程池: ```java import java.util.concurrent.*; public class CustomThreadFactory implements ThreadFactory { private final String threadNamePrefix; private final AtomicInteger threadNumber = new AtomicInteger(1); public CustomThreadFactory(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, threadNamePrefix + threadNumber.getAndIncrement()); // 设置线程属性,例如优先级、守护线程等 t.setPriority(Thread.NORM_PRIORITY); t.setDaemon(false); return t; } } public class Main { public static void main(String[] args) { // 创建自定义的ThreadFactory ThreadFactory threadFactory = new CustomThreadFactory("MyThread-"); // 创建线程池,并指定ThreadFactory ThreadPoolExecutor executor = new ThreadPoolExecutor( 5, 10, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), threadFactory); // 提交任务给线程池执行 executor.execute(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); }); // 关闭线程池 executor.shutdown(); } } ``` 在上面的示例中,我们创建了一个CustomThreadFactory类,实现了ThreadFactory接口,并重写了newThread方法。在newThread方法中,我们创建了一个新的Thread对象,并设置了线程的名称、优先级和守护线程属性。 然后,在主函数中,我们创建了一个ThreadPoolExecutor对象,并传入自定义的ThreadFactory。通过execute方法提交一个任务给线程池执行,任务会由自定义的线程池中的线程来执行。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值