gpt4 book ai didi

java - 在Java中串行执行Threadgroup中的线程

转载 作者:行者123 更新时间:2023-11-30 04:08:02 24 4
gpt4 key购买 nike

我目前正在学习 Java 线程的基础知识,我正在尝试编写一个程序来模拟 2 个团队的 2x200 接力赛。我想要有 2 个团队(每个团队由一个 ThreadGroup 代表),每个团队有 2 名成员,每个成员必须运行 200 m。这里只是通过for循环和打印来模拟运行。我无法找到串行运行线程组中的线程

的直接方法

这是 worker 的样子

public class RelayRunner implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 200; i++) {
String name = Thread.currentThread().getName();

if (i % 50 == 0) {
System.out.format("%s ran %d m \n", name, i);
}
}
}

}

这是主程序的样子

public class RelayRunnerMatch {

public static void main(String[] args) {

RelayRunner relayRunner = new RelayRunner();

ThreadGroup usa = new ThreadGroup("USA");
ThreadGroup germany = new ThreadGroup("GERMANY");

Thread usa1 = new Thread(usa, relayRunner, "usa1");
Thread germany1 = new Thread(germany, relayRunner, "germany1");

Thread usa2 = new Thread(usa, relayRunner, "usa2");
Thread germany2 = new Thread(germany, relayRunner, "germany2");

usa1.start();
germany1.start();

/* Now I would like to start the second thread in a group only if the first
thread in the same group has finished like in a real relay race. How??
*/
//usa1.join(); germany1.join();
//usa2.start(); germany2.start() --> Not good, usa2 must start immediately when usa1 has finished
}

}

我看不出 join() 在这里有什么帮助,因为它将等待两个线程完成,然后第二组运行者才能开始运行。我还意识到 activeCount() 只是一个估计,所以我也不确定是否使用它。有没有可能的解决方案,而无需求助于新的 Concurrent API 中的服务(因为我还没有进一步实现)?

最佳答案

public class Player1 implements Runnable{
private final CountDownLatch countDownLatch;
private final String s;
public Player1(CountDownLatch c, String s){
this.countDownLatch=c;
this.s=s;
}
@Override
public void run() {
for(int i=0;i<200;i++){
System.out.println(s+":"+i);
}
countDownLatch.countDown();
}

}


public class Player2 implements Runnable{
private final CountDownLatch countDownLatch;
private final String s;
public Player2(CountDownLatch c, String s){
this.countDownLatch = c;
this.s=s;
}
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException ex) {
Logger.getLogger(Player2.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i=0;i<200;i++){
System.out.println(s+":"+i);
}
}
}

驱动程序:

public static void main(String[] args){
Thread[] grp1 = new Thread[2];
Thread[] grp2 = new Thread[2];
CountDownLatch c1 = new CountDownLatch(1);
CountDownLatch c2 = new CountDownLatch(1);

grp1[0]=new Thread(new Player1(c1, "grp1:player1"));
grp1[1]=new Thread(new Player2(c2, "grp1:player2"));


grp2[0]=new Thread(new Player1(c2, "grp2:player1"));
grp2[1]=new Thread(new Player2(c2, "grp2:player2"));

grp1[0].start();
grp2[0].start();
grp1[1].start();
grp2[1].start();
}

关于java - 在Java中串行执行Threadgroup中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20286657/

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