gpt4 book ai didi

java - 为什么synchronized不能同步线程?

转载 作者:行者123 更新时间:2023-12-01 18:41:58 27 4
gpt4 key购买 nike

我已经设置了标志的值,但结果不是“add”和“sub”交替。为什么?当我查看结果时,它执行了两次“sub”方法。但是当'sub'方法结束时,标志的值将被设置为'false'。但结果却连续打印了两次“subxxxxx”。

class Resource {
private boolean flag = true;
private int num = 0;

// At here I have declared an add()
public synchronized void add() throws InterruptedException {
if (this.flag == false) {
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println("addition:"+Thread.currentThread().getName() + this.num);
this.flag = false;
super.notifyAll();
}

// At here I have declared an sub()
public synchronized void sub() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
this.flag = true;
super.notifyAll();
}
}

/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
new Thread(ad, "add").start();
new Thread(ad, "add").start();
new Thread(sub, "sub").start();
new Thread(sub, "sub").start();
}
}

最佳答案

您似乎假设当您的 wait() 调用完成时,flag 已更改为您在调用 wait() 之前想要的内容。没有这样的保证,特别是因为涉及两个以上的线程。您应该检查是否需要继续等待。另请参阅Wait until boolean value changes it state

但总的来说,这些构造的级别太低而无法使用(除非您想了解本质),您应该查看并发 utils 包以获取更简单的更高级别的构造(例如队列、锁存器、条件) .

关于java - 为什么synchronized不能同步线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915695/

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