[英]How to send interrupt signal to a thread from other thread
假設我有兩個線程使用同一類的實例,該實例充當監視器。 例如,使用類ABC'o'的相同實例的Thread1和Thread2。
現在,ABC類中有一個同步方法doProcess(),兩個線程都在調用該方法。 由於第一個線程處於wait()狀態,因此我在doProcess()中有一些條件。 現在,當第二個線程進入doProcess()時,有條件告訴它終止整個處理。
一種解決方案是通知第一個線程並更新一些標志以告知它不會再次阻塞並完成。
我在想什么,我可以從監視對象“ o”(就像notify和notifyAll一樣)發送任何信號到所有等待中斷和終止的線程嗎?
編輯的第一個解決方案:
sync doProcess()
{
while( you are thread1 and !flag )
{
wait(); //line 3
}
if( you are thread2)
{
flag = true;
notifyAll(); //can i send send any interrupt signal to terminate all threads in line 3 itself;
}
}
是。 方法是.interrupt()這將在接收線程中引發InterruptedException,應在run()方法中對其進行處理。 您仍然需要在正在運行的線程上設置標志,因為如果線程未阻塞,則不會發生InterruptedException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.