簡體   English   中英

當我想停止線程內的執行時,我可以使用“Thread.currentThread().interrupt()”嗎?

[英]Can I use "Thread.currentThread().interrupt()" when I want to stop execution inside a thread?

用於線程控制您正在使用“CountDownLatch”,最后您使用“latch.countDown()”來控制線程。 但是如果我在執行過程中使用“return”來分離線程,如下面的代碼,由於“latch.countDown()”不能被調用,線程保持等待。 所以我想使用“latch.countDown()”和“Thread.currentThread().interrupt()”而不是“return”,但我想知道這是否是正確的方法。 如果我錯了,我想要一些幫助。

CountDownLatch latch = new CountDownLatch();

public void run() {
  //....
  if (isNotExist) {
    retrun; //-> instead of "return" Can I use "latch.countDown()" and "Thread.currentThread().interrupt()" together?
  }
  //...
  latch.countDown()
}

如果我們使用CountdownLatch::countDown然后想等到閂鎖釋放,我們將使用CountdownLatch::await 我建議閱讀CountdownLatch的完整文檔

在當前線程上調用Thread::interrupt沒有明顯的效果,因為該線程現在沒有阻塞。 如果線程被阻塞,例如被 I/O 操作阻塞,它會產生影響。 但是話又說回來,如果當前線程被阻塞,它就不能中斷自己。 它可用於保留 state。 有關詳細信息,請參閱Hesey這個問題及其答案。

如果我們使用return ,我們會從當前方法返回。 這是與阻塞完全不同的構造。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM