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;
            }
        }
  • 相关阅读:
    selenium 定位元素的基本方法(6)
    selenium ,先了解html 基础知识(5)
    第 39 章 ThinkPHP--SQL 连贯操作
    第 39 章 ThinkPHP--模型初步(下)
    第 39 章 ThinkPHP--模型初步
    第 39 章 ThinkPHP--模块化和 URL 模式
    CSS属性编写顺序
    Ajax_使用jQuery 实现Ajax
    Ajax_数据格式三大类
    Ajax_使用XMLHttpRequest实现
  • 原文地址:https://www.cnblogs.com/200911/p/5281386.html
Copyright © 2011-2022 走看看