gpt4 book ai didi

Java线程问题

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

我正在像这样同步线程的对象:

synchronized(threadObject){
try{
threadObject.interrupt();
}catch(Exception ex){
//catch error here.
}finally{
threadObject.notifyAll();
}
}

现在,我的问题是:

  1. 可以中断一个线程在同步块(synchronized block)内,其被同步的对象是线程被中断?像示例代码。
  2. 我还能通知其他线程吗持有中断的线程目的?就像在示例代码中一样。

最佳答案

It is possible to interrupt a thread inside a synchronized block whose object that was synchronized was the thread to be interrupted? Like in the sample code.

是的。我不明白为什么那行不通。 synchronized 关键字与 interrupt 方法完全正交。 (请注意,与 awaitnotify 相反,您不需要在调用 interrupt 时拥有对象监视器.)

Can I still notify other threads holding the interrupted thread's object? Like in the sample code.

是的,只要您拥有对象监视器,就可以对任何对象调用 notifyAll。同样,wait/notify 机制与 interrupt 方法完全正交。


您的问题似乎表明您误解了synchronized 的用法。通常的用例是在表示您希望避免并发访问的某些资源的对象上进行同步。 线程本身很少代表这样的资源。

关于Java线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156645/

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