gpt4 book ai didi

java - 如何在 Java 中使用 wait()/notify()

转载 作者:搜寻专家 更新时间:2023-11-01 01:55:14 25 4
gpt4 key购买 nike

我知道有几个关于这个主题的讨论帖,但我只是在寻找一个关于如何在 Java 中使用 wait() 和 notify() 的非常基本的示例。 “非常初级”,我的意思是简单地打印一些东西。谢谢。

编辑:这是我迄今为止尝试过的方法,我得到了一个 IllegalMonitorStateException:



public void waiting() {
for(int i = 0; i < 10; i++) {
如果(我==5)
尝试 {
这个。等待();
} catch (InterruptedException e){

}
别的
System.out.println(i);
}
System.out.println("现在通知我");
这个。通知();
}

最佳答案

wait 和 notify 在同步块(synchronized block)中使用,同时使用线程在停止的地方挂起和恢复。

等待立即松开锁,而 Nofity 只有在遇到结束括号时才会离开锁。

public class Mythread implements Runnable{



public synchronized void goo(){

System.out.println("Before Wait");

wait();

System.out.println("After Wait");


}


public synchronized void foo(){

System.out.println("Before Notify");

notify();

System.out.println("After Notify");

}


public class Test{

public static void main(String[] args){

Thread t = new Thread(new Mythread);

t.start();

}
}

关于java - 如何在 Java 中使用 wait()/notify(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526374/

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