使用 ThreadPoolExecutor() 只运行一个线程

ham*_*alo 2 java multithreading 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);
}
Run Code Online (Sandbox Code Playgroud)

And*_*fat 5

为什么不使用公开了几种方便方法的工厂类呢?

例如:

您可以执行单线程线程池:

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

ExecutorService executorService = Executors.newSingleThreadExecutor();
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Run Code Online (Sandbox Code Playgroud)