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()方法来创建线程。

 

posted @   davygeek  阅读(1446)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2015-06-29 kvm 动态挂载硬盘
2015-06-29 [转] 如何让CloudStack使用KVM创建Windows实例成功识别并挂载数据盘
2015-06-29 Ubuntu终端Terminal常用快捷键
点击右上角即可分享
微信分享提示