【问题标题】:Run only one thread with ThreadPoolExecutor()使用 ThreadPoolExecutor() 只运行一个线程
【发布时间】:2015-05-13 07:51:00
【问题描述】:

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

【问题讨论】:

    标签: java multithreading threadpoolexecutor


    【解决方案1】:

    你为什么不使用暴露了几个方便方法的工厂类呢?

    例如:

    可以做单线程线程池:

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

    【讨论】:

    • 感谢 sfat,我同意 Executor 比这更容易,但我使用 ThreadPoolExecutor 很长时间了,现在我只想测试单个线程,不想改变其他任何东西。而且,ThreadPoolExecutor 是 Executor 的子类 :)。跟着你,我的提议正确吗?
    • @hamalo 是的,应该没问题。我还编辑了我的答案,向您展示了 newSingleThreadExecutor 的实现,它与您想要的一样,所以发疯吧。虽然我以后会推荐使用 Executors 工厂类,因为它有很大帮助。
    • 非常好!是的,我将来会使用 Executors 工厂类。谢谢斯法特!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2012-02-19
    • 2020-08-11
    • 1970-01-01
    • 2019-10-30
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多