繁体   English   中英

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

[英]Run 3 threads and wait in Java

我正在尝试编写一个只能同时运行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
  }
}

如您所见,大多数代码都是伪代码。 如果有人愿意,我可以将其发布,但这与主要问题无关紧要。

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

为了简单起见,我们可以在Java中使用线程池执行程序,这非常简单

使用executors方法创建3个线程的固定池。

编写一个for循环进行8次迭代,并在每个线程上调用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();

除非这是家庭作业,你可以使用Executors.newFixedThreadPool(3)该方法返回一个ExecutorService具有3个线程,最多要执行Runnable任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM