zoukankan      html  css  js  c++  java
  • Java并发包学习一 ThreadFactory介绍

      ThreadFactory翻译过来是线程工厂,顾名思义,就是用来创建线程的,它用到了工厂模式的思想。它通常和线程池一起使用,主要用来控制创建新线程时的一些行为,比如设置线程的优先级,名字等等。它是一个接口,接口中只有一个方法:

    /*
     *
     *
     *
     *
     *
     * Written by Doug Lea with assistance from members of JCP JSR-166
     * Expert Group and released to the public domain, as explained at
     * http://creativecommons.org/publicdomain/zero/1.0/
     */
    
    package java.util.concurrent;
    
    /**
     * An object that creates new threads on demand.  Using thread factories
     * removes hardwiring of calls to {@link Thread#Thread(Runnable) new Thread},
     * enabling applications to use special thread subclasses, priorities, etc.
     *
     * <p>
     * The simplest implementation of this interface is just:
     * <pre>
     * class SimpleThreadFactory implements ThreadFactory {
     *   public Thread newThread(Runnable r) {
     *     return new Thread(r);
     *   }
     * }
     * </pre>
     *
     * The {@link Executors#defaultThreadFactory} method provides a more
     * useful simple implementation, that sets the created thread context
     * to known values before returning it.
     * @since 1.5
     * @author Doug Lea
     */
    public interface ThreadFactory {
    
        /**
         * Constructs a new {@code Thread}.  Implementations may also initialize
         * priority, name, daemon status, {@code ThreadGroup}, etc.
         *
         * @param r a runnable to be executed by new thread instance
         * @return constructed thread, or {@code null} if the request to
         *         create a thread is rejected
         */
        Thread newThread(Runnable r);
    }

    下面定义MyThreadFactoryTest1类实现ThreadFactory接口的newThread方法:创建线程时候,为线程设置名字,代码如下:

    package concurrentMy.ThreadFactory;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * 
     * (类型功能说明描述)
     *
     * <p>
     * 修改历史:                                            <br>  
     * 修改日期            修改人员       版本             修改内容<br>  
     * -------------------------------------------------<br>  
     * 2016年3月15日 下午6:31:57   user     1.0        初始化创建<br>
     * </p> 
     *
     * @author        Peng.Li 
     * @version        1.0  
     * @since        JDK1.7
     */
    public class MyThreadFactoryTest1 implements ThreadFactory {
    
        private final AtomicInteger count = new AtomicInteger(0);
    
        // private final String namePrefix = "jmsgPool-" + count.incrementAndGet() + "-" + "PersistenceWrite" + "-thread-";
    
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("jmsgPool-" + count.incrementAndGet() + "-" + "PersistenceWrite" + "-thread");
            System.out.println("Create new thread, thread name: " + t.getName());
            return t;
        }
    
        /**
         * 
         * (测试) 
         *
         * @param args
         */
    
        public static void main(String[] args) {
            ExecutorService service = Executors.newFixedThreadPool(5, new MyThreadFactoryTest1());
    
            for (int i = 0; i <= 5; i++) {
                service.submit(new Runnable() {
    
                    @Override
                    public void run() {
                        System.out.println("Start execute...");
                    }
                });
            }
    
        }
    }

    Create new thread, thread name: jmsgPool-1-PersistenceWrite-thread
    Create new thread, thread name: jmsgPool-2-PersistenceWrite-thread
    Start execute...
    Create new thread, thread name: jmsgPool-3-PersistenceWrite-thread
    Start execute...
    Create new thread, thread name: jmsgPool-4-PersistenceWrite-thread
    Start execute...
    Create new thread, thread name: jmsgPool-5-PersistenceWrite-thread
    Start execute...
    Start execute...
    Start execute...

    JDK中默认的ThreadFactory

    在JDK的Executors类中有一个DefaultThreadFactory类,它实现了ThreadFactory,它是JDK中默认的线程工厂类,从源码可以看到这个线程工厂类为线程池中新创建的线程设置的名字为:

    /**
         * The default thread factory
         */
        static class DefaultThreadFactory implements ThreadFactory {
            private static final AtomicInteger poolNumber = new AtomicInteger(1);
            private final ThreadGroup group;
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            private 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;
            }
        }
  • 相关阅读:
    KALI LINUX 核心概念讲解,持续更新
    KALI LINUX 工具大全之密码破解 --- BruteSpray ( 暴力喷雾 )
    android studio的 gradle 依赖同步错误解决方法
    安卓逆向的初步研究--从某恋app入手
    nc浏览器的十宗罪
    手机重要文件目录(换新机可能要用到)
    国产手机的谷X服务
    安卓手机设置的那些琐事
    办公中遇见的那些问题
    装系统遇到的那些问题
  • 原文地址:https://www.cnblogs.com/200911/p/5281386.html
Copyright © 2011-2022 走看看