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

时间:2015-05-13 07:51:01

标签: 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);
}

1 个答案:

答案 0 :(得分:4)

为什么不使用工厂类来暴露几种方便的方法?

例如:

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

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());