gpt4 book ai didi

java - 无法让 notificationAll 按预期工作

转载 作者:行者123 更新时间:2023-11-30 07:25:00 25 4
gpt4 key购买 nike

我在 Runnable 类 A 中有一个函数:

public void function1(){
synchronized(lock){
function2.decrease();
lock.notifyAll();
System.out.print(function2.getValue());
}

我在 Runnable 类 B 中有另一个函数:

public void function3(){
try{
synchronized(lock){
while(!(function2.getValue() != 0)){
lock.wait();
}
Thread.sleep(1000);
System.out.println(function2.getValue() + 10);
}
}catch(InterruptedException e){
System.err.println(e);
}
}

当我运行程序时,即使等待条件的计算结果为 true,它始终会先在 function1 中打印,然后再在 function3 中打印。

在打印 function1 中的值之前,我需要做什么来打印 function3 中的值?

最佳答案

看起来您可能多次运行 function1 来减少 function2 的值,然后在 function3 中执行 while 循环检查。因此,首先,在这种情况下,期望 function1 在 function3 之前打印是完全正常的,因为 function3 在其打印语句之前等待 1 秒,而在此期间 function1 可以做任何它想做的事情。

其次,也许更优雅的解决方案是在 function1 中检查 function2 的值,然后在它 == 0 的情况下使用 notificationAll() 。这样, function3 中就不需要 while 循环,它只使用 wait () 并等待来自 function1 的 notificationAll() 调用。

我的意思是:功能1添加

if(function2.getValue() == 0)
lock.notifyAll();

Function3 删除 while 循环

// no while loop
lock.wait();

然后回答原来的问题,为了确保 function3 首先在 function1 中的 if 语句内打印,请在 notificationAll() 之后调用 lock.wait() 并在 function3 末尾添加 notifyAll() 。

下面演示了可编译的类。

public class StackSyncProb{
private volatile int function2;
private Object lock = new Object();

public static void main(String[] args){
StackSyncProb s = new StackSyncProb(3); // function2 starts at 3
// start function3, which waits
s.runFunction3();
// decrement using function1 until hit 0 (in this case, 3 times)
for(int i = 0; i < 3; i++){
s.runFunction1();
}
}

public StackSyncProb(int v){
function2 = v;
}

public void runFunction1(){
new Thread(new Run1()).start();
}

public void runFunction3(){
new Thread(new Run2()).start();
}

public class Run1 implements Runnable{
@Override
public void run(){
function1();
}
public void function1(){
try{
synchronized(lock){
function2--;
// Use if statement to check inside function1 instead of in function3
if(function2 == 0){
lock.notifyAll();
// After notifying, wait until function3 done
lock.wait();
}
System.out.println("function1: " + function2);
}
}catch(InterruptedException e){}
}
}

public class Run2 implements Runnable{
@Override
public void run(){
function3();
}
public void function3(){
try{
synchronized(lock){
// No while loop
lock.wait();
Thread.sleep(1000);
System.out.println("function3: " + (function2 + 10));
// Notify function1 it can complete and print
lock.notifyAll();
}
}catch(InterruptedException e){
System.err.println(e);
}
}
}
}

关于java - 无法让 notificationAll 按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928824/

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