Executors.newSingleThreadExecutor()和Executors.newFixedThreadPool(1)之间的任何区别

Che*_*eng 1 java

我想知道,Executors.newSingleThreadExecutor()Executors.newFixedThreadPool(1)之间有什么区别

以下是从javadoc中选取的

与其他等效的newFixedThreadPool(1)不同,保证返回的执行程序不可重新配置以使用其他线程.

我尝试下面的代码,似乎没有区别.

package javaapplication5;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author yan-cheng.cheok
 */
public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        //ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
        ExecutorService threadExecutor = Executors.newFixedThreadPool(1);
        threadExecutor.submit(new BadTask());
        threadExecutor.submit(new Task());      
    }

    class BadTask implements Runnable {
        public void run() {
            throw new RuntimeException();
        }
    }

    class Task implements Runnable {
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("[LIVE]");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的理解最可能出错了:)

Thi*_*ilo 7

就像它说:

与其他等效的newFixedThreadPool(1)不同,保证返回的执行程序不可重新配置以使用其他线程.

不同之处在于(仅)SingleThreadExecutor不能稍后调整其线程大小,您可以通过调用ThreadPoolExecutor #setCorePoolSize(需要先进行强制转换)来使用FixedThreadExecutor.

  • ((的ThreadPoolExecutor)的newFixedThreadPool(1))setCorePoolSize(3). (3认同)