gpt4 book ai didi

java - 如何逐步执行所有线程

转载 作者:行者123 更新时间:2023-12-02 10:50:30 25 4
gpt4 key购买 nike

如果每个任务(线程)有多个阶段。那么如何保证所有的任务执行stage 1然后执行stage 2等等。例如,如何修改以下代码以使我的输出为:任务 1 的第 1 阶段,任务 2 的第一阶段,任务 3 的第 1 阶段,任务 1 的第 2 阶段,任务 2 的第 2 阶段,任务 3 的第 2 阶段,等等...

public class Task implements Runnable{
public String name;
static Random random = new Random();

Task(String name){
this.name=name;
}

public static void main(String args[]) {
ExecutorService ex = Executors.newFixedThreadPool(6);
ex.submit(new Task("Task 1"));
ex.submit(new Task("Task 2"));
ex.submit(new Task("Task 3"));
}

public static void getRandomsleep() {
try {
Thread.sleep(random.nextInt(5000));
} catch (InterruptedException e) {
// ...
} }

public void run() {
System.out.println("thread name" + this.name);
getRandomsleep();
System.out.println("stage 1 of " + this.name);
getRandomsleep();
System.out.println("stage 2 of " + this.name);
getRandomsleep();

}
}

最佳答案

可以使用CyclicBarrier来解决此类问题。

public class CyclicBarrierDemo {

public static void main(String args[]) {
CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService ex = Executors.newFixedThreadPool(3);
ex.submit(new Task("Task 1", barrier));
ex.submit(new Task("Task 2", barrier));
ex.submit(new Task("Task 3", barrier));
}

static class Task implements Runnable {
String name;
CyclicBarrier barrier;

Task(String name, CyclicBarrier barrier) {
this.name = name;
this.barrier = barrier;
}

void doWork() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ...
}
}

public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("stage " + i + " of " + this.name);
doWork();
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
return;
}
}
}
}
}
输出
stage 1 of Task 1
stage 1 of Task 2
stage 1 of Task 3
stage 2 of Task 1
stage 2 of Task 2
stage 2 of Task 3
stage 3 of Task 3
stage 3 of Task 1
stage 3 of Task 2

关于java - 如何逐步执行所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com