[英]Executing threads in a Threadgroup serially in Java
我目前正在学习Java线程的基础知识,并且试图编写一个模拟2个团队进行2x200接力赛的程序。 我想有2个小组(每个小组由ThreadGroup代表),每个小组有2个成员,每个成员必须运行200 m。 在这里,运行只是通过循环for循环和打印来模拟的。 我找不到连续运行线程组中线程的直接方法
这是工人的样子
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()只是一个估计,所以我不确定是否也可以使用它。 是否有可能在不借助新的并发API中提供服务的情况下解决方案(因为我还没有进一步了解)?
您可以创建两个警棍对象并在相应的警棍上进行synchronize
,因此第二个线程将不得不等到第一个线程释放警棍-或使用java.util.concurrent.locks
-package中的一些锁来实现相同目的。 但是您的接力成员将争夺谁先获得接力棒,而您无法定义一些真实的订单。
但是正如Jarrod所说的那样:当您必须依次执行多个任务时,最好在同一线程上执行它们:拥有一些运行程序对象,并将它们添加到相应中继线程的队列中,该中继线程将在其后调用运行方法另一个。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.