Java中的线程池

kle*_*ens 5 java multithreading android

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

private ExecutorService threadExecutor = Executors.newFixedThreadPool( 20 );
Run Code Online (Sandbox Code Playgroud)

然后我创建了一些Runnable对象.之后,我不时地执行我的ThreadPool传递相同的Runnable对象:

threadExecutor.execute(serverRunnable);
Run Code Online (Sandbox Code Playgroud)

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

Executors.newFixedThreadPool( 20 );
Run Code Online (Sandbox Code Playgroud)

从20到100个ThreadPool将工作更长时间.任何人都可以解释为什么ThreadPool停止工作?

PS.我在Android中编写此代码

lig*_*303 3

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

看来您的可运行程序不会终止 - 这样,它将在固定时间后超过 20 个线程。如果您的可运行程序正常终止 - 您将能够无限长时间地使用您的执行器。