wait(some time) 是否必须始终在同步方法中?

发布于 2025-01-03 10:30:27 字数 304 浏览 4 评论 0原文

我有多线程应用程序。有时由于外部网络原因,某些线程会发生异常。我认为使用例如 wait(60000) - 1 分钟来重新连接。 我应该明确地放入同步方法,例如:

public void synchronized reconnect(){
     wait(60000);
................. }

或者可能:

public void reconnect(){
     wait(60000);
................. }

谢谢。

I have multithreaded application. Sometime in some thread happens exception for external network reason. I think use e.g. wait(60000) - 1 minute to re-connect.
Should I explicitly put in synchronized method e.g.:

public void synchronized reconnect(){
     wait(60000);
................. }

or it possible:

public void reconnect(){
     wait(60000);
................. }

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦÷微暖 2025-01-10 10:30:27

正如尤金所写,当前线程必须获取对象的锁。不必通过同步方法来完成。您还可以通过显式同步来获取锁:

public void reconnect() {
   // some code 

   synchronized (this) {
      wait(60000);
   }

   // some other code
}

这取决于您需要实现的目标。

As Eugene wrote, current thread must acquire lock on object. It is not necessary done by synchronized method. You also may acquire lock by explicit synchronizing:

public void reconnect() {
   // some code 

   synchronized (this) {
      wait(60000);
   }

   // some other code
}

It depends on that you need to achieve.

迷离° 2025-01-10 10:30:27

必须如此!您必须先获取对象的锁,然后才能真正等待。

干杯,尤金。

It has to be! You must acquire the lock of the Object before you can actually wait.

Cheers,Eugene.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文