【问题标题】:Thread pool in JavaJava中的线程池
【发布时间】:2012-01-09 09:58:03
【问题描述】:

我使用 ThreadPool 在 Java 中编写应用程序。首先我创建新的线程池:

private ExecutorService threadExecutor = Executors.newFixedThreadPool( 20 );

然后我创建一些 Runnable 对象。之后,我不时执行我的 ThreadPool 并传递给他相同的 Runnable 对象:

threadExecutor.execute(serverRunnable);

我每 20 秒执行一次这个线程池。我的问题是 threadExecutor 停止工作大约 5 分钟。它只是不执行 Runnable 对象。我注意到当我增加参数时:

Executors.newFixedThreadPool( 20 );

从 20 到例如100 ThreadPool 将工作更长时间。谁能解释一下为什么 ThreadPool 停止工作?

附言。我在 Android 中编写此代码

【问题讨论】:

  • 请从您的serverRunnable 对象中发布代码。
  • 您的 Runnable 是否正确停止?如果他们从未结束他们的run() 方法,您的池将被耗尽,execute() 将锁定等待池中的一个插槽可用。
  • 我使用 serverRunnable 为例。我将许多不同的 Runnable 传递给 ThreadPoll,它们都停止了。他们中的一些人做一些琐碎的工作,在日志中写一些东西。
  • 我认为我的 run() 正确停止。我没有 while 循环或类似的东西。

标签: java android multithreading


【解决方案1】:

首先,如果您想将任务安排为每 20 秒执行一次,请尝试使用 ScheduledThreadPoolExecutor 代替:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

您的可运行对象似乎没有终止 - 这样它会在固定时间后超过 20 个线程。如果你的 runnable 正常终止 - 你将能够无限长地使用你的 executor。

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2016-05-15
    • 2017-07-18
    • 2018-07-24
    相关资源
    最近更新 更多