我正在尝试编写一个只能同时运行X(比方说3)线程的类。我有8个线程需要执行,但我只想让3一次运行,然后等待。一旦一个当前运行的线程停止,那么它将启动另一个线程。我不太清楚该怎么做。我的代码如下所示:
public class Main {
public void start() {
for(int i=0; i<=ALLTHREADS; i++) {
MyThreadClass thread = new MyThreadClass(someParam, someParam);
thread.run();
// Continue until we have 3 running threads, wait until a new spot opens up. This is what I'm having problems with
}
}
}
public class MyThreadClass implements Runnable {
public MyThreadClass(int param1, int param2) {
// Some logic unimportant to this post
}
public void run() {
// Generic code here, the point of this is to download a large file
}
}正如您在上面看到的,大部分代码都被删除了伪代码。如果有人愿意的话,我可以发出去,但这对主要问题并不重要。
发布于 2014-05-12 02:57:39
这里应该使用线程池机制来运行多个线程。
为了简单起见,我们可以使用java中的线程池执行器,这非常容易。
使用executors方法创建一个由3个线程组成的固定池。
为8次迭代编写一个for循环,并在每个线程上调用execute,每次只运行3个线程。
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 8; i++) {
Task task = new Task(someParam, someParam);
executor.execute(task);
}
executor.shutdown();发布于 2014-05-12 02:38:32
除非这是作业,否则您可以使用Executors.newFixedThreadPool(3)来执行Runnable任务,它返回最多3个线程的ExecutorService。
https://stackoverflow.com/questions/23600240
复制相似问题