2016-11-05 23 views
1

當線程處於睡眠狀態時,它仍然保存着對象的鎖,當它中斷時,它是否釋放鎖並進入就緒狀態或將它繼續執行而不改變狀態?中斷對象上的睡眠線程釋放鎖的異常

+0

睡眠狀態不存在,你是指WAITING? –

+0

睡眠你是指'Thread.sleep(x)'或'obj.wait()'? –

+0

但是如果你調用* Thread.sleep()*爲什麼你應該繼續鎖定資源?也許你應該先釋放,並嘗試從睡眠恢復時重新獲得鎖定。無論如何,由於threadInterruption是一個異常,它取決於如何處理異常。我會期待一個最後的塊來清理。 –

回答

2

當它被中斷時,它是否釋放鎖並進入就緒狀態 或者它會繼續執行而不改變狀態?

被中斷的線程只是狀態更改(已設置的標誌)而不是狀態更改,它對是否釋放鎖沒有影響。

只有在相應的對象實例上調用wait(有或沒有超時),或者它將從同步塊退出,被中斷或不會改變任何事情時,持有對象監視器的線程纔會釋放它規則。


下面是一個簡單的代碼,給出了這個概念:

// Used to make sure that thread t holds the lock before t2 
CountDownLatch latch = new CountDownLatch(1); 
Thread t = new Thread(
    () -> { 
     synchronized (someObject) { 
      // Release t2 
      latch.countDown(); 
      for (int i = 1; i <= 2; i++) { 
       try { 
        System.out.println("Sleeping " + i); 
        // Sleep 2 sec and keep holding the lock 
        Thread.sleep(2_000L); 
        System.out.println("Sleep over " + i); 
       } catch (InterruptedException e) { 
        System.out.println("Interrupted " + i); 
       } 
      } 
     } 
    } 
); 
Thread t2 = new Thread(
    () -> { 
     try { 
      // Wait to be release by t 
      latch.await(); 
     } catch (InterruptedException e) { 
      throw new IllegalStateException(e); 
     } 
     System.out.println("Trying to get in"); 
     synchronized (someObject) { 
      System.out.println("In"); 
     } 
    } 
); 
// Start the threads 
t.start(); 
t2.start(); 
// Waiting 1 sec (< 2 sec) only before interrupting t 
Thread.sleep(1_000L); 
// Interrupt t 
t.interrupt(); 

輸出:

Trying to get in 
Sleeping 1 
Interrupted 1 
Sleeping 2 
Sleep over 2 
In 

正如你可以在輸出線t2進入同步看到只有當線程t從同步中退出時纔會阻塞(獲取鎖定) zed塊。線程t已被中斷的事實並未使其釋放該鎖。

+0

這足夠清楚了嗎? –