gpt4 book ai didi

java - 线程同步中的 While 与 If

转载 作者:行者123 更新时间:2023-11-29 09:26:57 34 4
gpt4 key购买 nike

我有两组代码,其中我尝试一个接一个地打印字母和数字。一组使用“while 循环”,另一组使用“if”。

public class Alphabets {

public static void main(String[] args) {

AN an= new AN(false);

Thread t1=new Thread(new Runnable() {

@Override
public void run() {
try {
an.Alpha();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Thread t2= new Thread(new Runnable() {
@Override
public void run() {
try {
an.numbers();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}

class AN {
boolean flag;
AN(boolean flag) {
this.flag=flag;
}
synchronized void Alpha() throws InterruptedException {
for(char i='A'; i<='Z';i++) {
while(flag==false) { // I have replaced "while" with "if" in my second code
System.out.println(+i);
notifyAll();
flag=true;
}
wait();
}
}
synchronized void numbers() throws InterruptedException {
for(int i=1;i<=26;i++) {
while(flag==true) {// I have replaced "while" with "if" in my second code
System.out.println(+i);
notifyAll();
flag=false;
}
wait();
}
}
}

设置 1 与“while”循环给出以下输出:

65 1 66 2 67 3 68 4

带有“if”的设置 2 给出以下输出:

65 1 67 3 69 5 71 7

请注意,65 66 是 A、B 等的 ascii 码。

任何人都可以解释为什么这两个代码的行为是这样的。我无法弄清楚。请详细说明。

最佳答案

答案就在spurious wakeup .这意味着任何 wait 语句都可能在没有任何人实际调用 notify 的情况下自发唤醒。在这种情况下,for 循环前进了另一步,实际上没有打印任何东西,因为标志仍然处于错误状态。

使用 if 或 while 对代码本身没有影响,它恰好更频繁地触发实际问题。

解决这个问题的方法是循环等待直到状态真正改变:

for(char i='A'; i<='Z';i++) {
if(flag==false) {
System.out.println(+i);
notifyAll();
flag=true;
}
while (flag == true) { // spurious wakeup prevention
wait();
}
}

关于java - 线程同步中的 While 与 If,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52951493/

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