运行3个线程并在Java中等待

use*_*544 1 java multithreading

我正在尝试编写一个只能同时运行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
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面所看到的,大多数都是伪代码.如果有人愿意,我可以发布它,但它对主要问题不重要.

Kar*_*G C 7

你应该在这里使用线程池机制来运行多个线程.

为了方便我们可以在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();
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 6

除非这是作业,否则您可以使用Executors.newFixedThreadPool(3)返回ExecutorService最多3个线程来执行Runnable任务.