保持一定数量的运行线程(JAVA)

时间:2013-03-12 16:11:41

标签: java multithreading

我想实现一个软件,确保10 threads始终运行同一个类

所有threads将在一段秒后随机终止,但是,我想确保一旦它们被终止,它们会被新创建的threads立即替换。

你知道是否有可用的图书馆吗?

非常感谢, 维拉德

2 个答案:

答案 0 :(得分:5)

而是使用线程池。 Java Executor框架提供了它。

ExecutorService executor = Executors.newFixedThreadPool(10);

答案 1 :(得分:0)

   ExecutorService  executorPool = Executors.newFixedThreadPool(noOfThreads);

public static ExecutorService newFixedThreadPool(int nThreads)

Creates a thread pool that reuses a fixed set of threads operating off a

shared unbounded queue. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.

Parameters:
    nThreads - the number of threads in the pool 
Returns:
    the newly created thread pool