gpt4 book ai didi

java - 为什么我们应该在 try block 中使用 wait() 方法?我们可以在 try block 之外使用 wait() 方法吗?

转载 作者:行者123 更新时间:2023-11-29 04:28:51 25 4
gpt4 key购买 nike

这里我在 try block 中使用 wait() 方法来实现线程间的相互通信。我在 try block 外使用了 wait 方法,但它显示异常。

try
{
System.out.println(" why we should use wait() method in try block ");
wait();
}
catch()
{
}
}

最佳答案

Q: Why should we use wait() method inside the try block?

您在 synchronized block 或 synchronized 方法中使用 wait()

synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}

还有另一种方法......

synchronized (this) {
this.isTeapot = true;
this.notify();
}

为什么?

  • 因为规范是这么说的。
  • 因为如果不这样做,您将得到一个 IllegalMonitorStateException

但为什么呢?

  • 因为没有这个限制就不可能安全地实现等待/通知条件变量。该要求对于线程安全至关重要;即避免竞争条件和内存异常。

try block 不是强制性的。如果您需要在该级别 处理异常,请使用try block 。如果没有,让它传播。这包括 InterruptedException ... 虽然因为它是一个已检查的异常,如果您没有在本地捕获它,则需要在方法的 throws 子句中声明它。但这只是正常的 Java 异常处理。没什么特别的。

例如:

try {
synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}

(有关上述示例的解释,请参阅 Why would you catch InterruptedException to call Thread.currentThread.interrupt()?。)

Q: Can we use wait() method outside the try block?

您不能在 synchronized block 或 synchronized 方法之外调用 wait()。 (见上文。)

try block 不是强制性的。 (见上文。)

关于java - 为什么我们应该在 try block 中使用 wait() 方法?我们可以在 try block 之外使用 wait() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742852/

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