zoukankan      html  css  js  c++  java
  • 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()方法来创建线程。
  • 相关阅读:
    nginx下配置WebSocket连接错误Error:Unexpected response code 404
    qqzone/tx云登录所用g_tk/x-csrfcode获取
    自动化工具Ansible的使用操作
    Docker可视化图形工具Portainer
    centos下.Netcore的docker容器部署出现“The type initializer for 'Gdip' threw an exception.”
    苹果开发者公司账号申请全流程以及出现的问题(2021更新)
    Certbot配置Let's Encrypt的https_ssl证书以及过程中出现的问题(2021更新)
    开源的一小步----开源类库传至Maven中央仓库
    使用微软的Office Online实现Office,word文档的在线浏览,编辑 ,以及不能正常查看文档问题
    Linux安装Mysql5.6
  • 原文地址:https://www.cnblogs.com/davygeek/p/5625572.html
Copyright © 2011-2022 走看看