[英]How to wait for one of the running threads in ExecutorService to finish to assign another task
我有使用固定大小的线程将任务分配给ExecutorService的循环,我希望主程序等待 threadPool释放其线程之一来为其分配另一个任务。
这是我的示例代码:在此示例代码中,我想finished!
最后打印出来,并想使用ExecutorService。
public static void main(String[] args) {
ExecutorService ex = Executors.newFixedThreadPool(3);
for(int i=0; i< 100; i++) {
ex.execute(new TestThread(i)); // I want the program wait here for at least one thread to free
}
System.out.println("finished!");
}
private static class TestThread implements Runnable {
private int i;
public TestThread(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println("hi: " + i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我了解您希望提交作业的线程在执行器服务中没有免费的,随时可用的工作线程的情况下阻塞。 这对施加背压很有用。
执行程序服务的核心是“简单地”由可运行队列和工作线程池组成。
您可以通过构建具有固定大小(在您的情况下,大小为1)的工作队列的执行程序服务来获得此行为。
在代码中:(请注意,您的调用者线程在提交最后一个作业后仍将继续;它不会等待该作业完成)
package stackOv;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class BackPressure {
public static void main(String[] args) {
// this is the backing work queue; in this case, it is of bounded size
ArrayBlockingQueue<Runnable> q = new ArrayBlockingQueue<>(1);
ExecutorService ex = new ThreadPoolExecutor(3, 3, 30, TimeUnit.SECONDS, q,
new ThreadPoolExecutor.CallerRunsPolicy());
for(int i=0; i< 100; i++) {
ex.execute(new TestWork(i));
}
System.out.println("finished!");
}
private static class TestWork implements Runnable {
private int i;
public TestWork(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println("hi: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
所有你需要的是:
ex.awaitTermination();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.