运行 ThreadPoolExecutor() 只有一个线程

Run only one thread with ThreadPoolExecutor()

我使用 ThreadPoolExecutor() 为我的应用程序 运行 多线程。我想用单线程进行测试,所以在这种情况下我设置 nb_threads = 1 。但是我不确定它是否正确所以你能帮我只带一个线程吗?

这是我的部分代码:

private ThreadPoolExecutor executor = null;
public static int NB_THREADS_MAX = 8;

public void submit(Runnable inRunnable) {
        if (executor == null) {

        /*Choice exactly the number of threads that relates the number of available processors*/
        nb_threads = NB_THREADS_MAX < (tmp = Runtime.getRuntime().availableProcessors())
                      ? NB_THREADS_MAX
                      : tmp;
        executor = new ThreadPoolExecutor(nb_threads, nb_threads, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); /*In this case, the pool size is fixed*/
        }

        executor.submit(inRunnable);
}

你为什么不利用工厂 class 公开了几个方便的方法?

例如:

可以做单线程线程池:

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

ExecutorService executorService = Executors.newSingleThreadExecutor();

如果你检查 newSingleThreadExecutor 源代码你会发现这个

 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
 }

要添加固定池,使用可用的处理器,您可以执行以下操作:

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


ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());