---
title: "Concurrent - Executors - newSingleThreadExecutor()"
author: "fairy_xzc"
date: "2016-12-07T15:40:00Z"
tags: []
categories: ["编程语言"]
slug: "concurrent-executors-newsinglethreadexecutor"
draft: false
lastmod: "2016-12-07T15:43:54Z"
id: 2343526
url: "https://agilestyle.iteye.com/blog/2343526"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2343526](/blog/2343526)**

 

使用newSingleThreadExecutor()方法可以创建单一线程池，单一线程池可以实现以队列的方式来执行任务。

![](http://dl2.iteye.com/upload/attachment/0121/8202/1a427357-eb7b-3bc5-b042-e545e1d7600f.png)

SingleThreadPoolTest.java

```
package org.fool.java.concurrent.executor.single;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SingleThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 3; i++) {
            executorService.execute(new MyThread(String.valueOf(i + 1)));
        }
    }

    public static class MyThread implements Runnable {

        private String name;

        public MyThread(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " name=" + name + " begin " + System.currentTimeMillis());
            System.out.println(Thread.currentThread().getName() + " name=" + name + " end " + System.currentTimeMillis());
        }
    }
}
```

Run

![](http://dl2.iteye.com/upload/attachment/0121/8206/49b69a74-5f98-3e67-a6a1-80af7a27629b.png)  
Note:

执行了3次，但是只有1个线程在运行

 

#### 使用newSingleThreadExecutor(ThreadFactory threadFactory)定制线程工厂

SingleThreadPoolTest2.java

```
package org.fool.java.concurrent.executor.single;

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

public class SingleThreadPoolTest2 {
    public static void main(String[] args) {
        MyThreadFactory myThreadFactory = new MyThreadFactory();

        ExecutorService executorService = Executors.newSingleThreadExecutor(myThreadFactory);

        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " invoked...");
                }
            });
        }

    }

    public static class MyThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("My Own Thread " + (int) (Math.random() * 10 + 1));

            return thread;
        }
    }
}
```

Run

![](http://dl2.iteye.com/upload/attachment/0121/8208/acc6e546-ffda-3159-b655-02497923ef30.png)

Note:

执行了10次，但是只有1个线程在运行