繁体   English   中英

使用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);
}

您为什么不利用工厂类来公开几种方便的方法?

例如:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM