gpt4 book ai didi

java - 如何用四线打印 1 到 10

转载 作者:行者123 更新时间:2023-12-02 09:31:37 26 4
gpt4 key购买 nike

如何使用 4 个线程打印 1 到 10,并且当打印数字 10 时,线程通知所有其他线程终止。我想要这样的输出

t1 -1
t2 -2
t3 -3
t4 -4
t1 -5
t2 -6
t3 -7
t4 -8
t1-9
t2 -10
all thread stop

我尝试过这个,但我知道这不是正确的方法,谁能告诉我正确的方法,我在互联网上找不到任何正确的答案,如果有人告诉我正确的方法,那将是一个很大的帮助

public class NumberGame {
public static void main(String[] args) {

PrintSequenceRunnable.startFrom("T1");

new Thread(new PrintSequenceRunnable("T1", "T2")).start();
new Thread(new PrintSequenceRunnable("T2", "T3")).start();
new Thread(new PrintSequenceRunnable("T3", "T1")).start();
}
}

class PrintSequenceRunnable implements Runnable {

private final String name;
private final String next;

private static String moveTo;

private static int value = 1;

PrintSequenceRunnable(String name, String next) {
this.name = name;
this.next = next;
}

static void startFrom(String start) {
moveTo = start;
}



@Override
public void run() {
do {
synchronized (moveTo) {
if (name.equals(moveTo)) {
System.out.println(name + "-" + (value++));
moveTo = next;
} else {
uselessCounter++;
}
}
} while (value < 10);

}

}

最佳答案

首先,如果您使用并发搜索线程安全变量、对象等。永远不要使用这样的东西 private static int value = 1; 使用原子变量,例如 private static AtomicInteger value = new AtomicInteger(0); 做好你的工作,直到达到你的目标任务完成。如果作业完成,则中断线程。我有这段代码

类 PrintSequenceRunnable 实现 Runnable {

private final String name;
private final String next;

private static String moveTo;

private static AtomicInteger value = new AtomicInteger(0);

PrintSequenceRunnable(String name, String next) {
this.name = name;
this.next = next;
}

static void startFrom(String start) {
moveTo = start;
}



@Override
public void run() {
do {
if (name.equals(moveTo) && value.get() < 10) {
System.out.println(name + "-" + (value.incrementAndGet()));
moveTo = next;
}
} while (value.get() < 10);
}

}

public static void main (String[] args) {
PrintSequenceRunnable.startFrom("T1");

new Thread(new PrintSequenceRunnable("T1", "T2")).start();
new Thread(new PrintSequenceRunnable("T2" , "T3")).start();
new Thread(new PrintSequenceRunnable("T3", "T4")).start();
new Thread(new PrintSequenceRunnable("T4", "T1")).start();
}

输出:

T1-1
T2-2
T3-3
T4-4
T1-5
T2-6
T3-7
T4-8
T1-9
T2-10

关于java - 如何用四线打印 1 到 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910339/

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