1. 程式人生 > >[Java併發包學習三]ThreadFactory介紹

[Java併發包學習三]ThreadFactory介紹

概述

ThreadFactory翻譯過來是執行緒工廠,顧名思義,就是用來建立執行緒的,它用到了工廠模式的思想。它通常和執行緒池一起使用,主要用來控制建立新執行緒時的一些行為,比如設定執行緒的優先順序,名字等等。它是一個介面,介面中只有一個方法:

1
2
3
4
5
6
7
8
9
/**
 * 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);

子類實現此方法並在其中完成自定義的行為。

實驗

下面我們通過一個簡單的實驗來解釋ThreadFactory的作用,下面的程式碼首先建立一個類MyThreadFactoryTest,實現了ThreadFactory,newThread()方法中做了一些簡單的行為:

  • 建立新執行緒時,為執行緒設定一個名字;
  • 建立新執行緒時,在控制檯列印一條提示資訊,並附上新執行緒的名字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.winwill.thread;

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

/**
* @author qifuguang * @date 15/8/11 20:28 */
public class MyThreadFactoryTest implements ThreadFactory { private final AtomicInteger count = new AtomicInteger(0); public Thread newThread(Runnable r) { int c = count.incrementAndGet(); Thread t = new Thread(r); t.setName("test_thread_no." + c); System.out.println("Create new thread, thread name: " + t.getName()); return t; } public static void main(String[] args) throws Exception { ExecutorService service = Executors.newFixedThreadPool(5, new MyThreadFactoryTest()); for (int i = 0; i < 5; i++) { service.submit(new Runnable() { public void run() { System.out.println("Start execute..."); } }); } } }

執行這段程式會得到如下的結果:

Create new thread, thread name: test_thread_no.1
Create new thread, thread name: test_thread_no.2
Start execute…
Start execute…
Create new thread, thread name: test_thread_no.3
Start execute…
Create new thread, thread name: test_thread_no.4
Start execute…
Create new thread, thread name: test_thread_no.5
Start execute…

可以看到,執行結果符合我們的預期。

JDK中預設的ThreadFactory

在JDK的Executors類中有一個DefaultThreadFactory類,它實現了ThreadFactory,它是JDK中預設的執行緒工廠類,從原始碼可以看到這個執行緒工廠類為執行緒池中新建立的執行緒設定的名字為:

pool-[執行緒池編號]-thread-[該執行緒池的執行緒編號]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
    * 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;
       }
   }