gpt4 book ai didi

java - 使用 notifyAll() 的多线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:57:39 27 4
gpt4 key购买 nike

我正在编写一个 java 程序,打印经过的秒数,每 5 秒打印一条消息。这是一个示例输出:

0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello 

如何删除 boolean 变量 printMsg?有没有更好的线程设计可以做到这一点?

目前,如果没有 printMsg,程序将在 5、10、15 等的 1/10 秒内打印多个“hello”。

class Timer {
private int count = 0;
private int N;
private String msg;
private boolean printMsg = false;

public Timer(String s, int N) {
msg = s;
this.N = N;
}

public synchronized void printMsg() throws InterruptedException{
while (count % N != 0 || !printMsg)
wait();
System.out.print(msg + " ");
printMsg = false;
}

public synchronized void printTime() {
printMsg = true;
System.out.print(count + " ");
count ++;
notifyAll();
}

public static void main(String[] args) {
Timer t = new Timer("hello", 5);
new TimerThread(t).start();
new MsgThread(t).start();
}
}

class TimerThread extends Thread {
private Timer t;
public TimerThread(Timer s) {t = s;}

public void run() {
try {
for(;;) {
t.printTime();
sleep(100);
}
} catch (InterruptedException e) {
return;
}
}
}

class MsgThread extends Thread {
private Timer t;
public MsgThread(Timer s) {t = s;}

public void run() {
try {
for(;;) {
t.printMsg();
}
} catch (InterruptedException e) {
return;
}
}
}

最佳答案

不需要使用 printMsg 标记,当 count % N == 0 时,只需使用 notifyAll 即可

public synchronized void printMsg() throws InterruptedException {
wait();
System.out.print(msg + " ");
}

public synchronized void printTime() {
System.out.print(count + " ");
count++;
if (count % N == 0){
notifyAll();
}
}

关于java - 使用 notifyAll() 的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349811/

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