ant76050391
ant76050391

Reputation: 23

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

Used for thread control You are using "CountDownLatch", and at the end you are using "latch.countDown()" to control the thread. But if I use "return" to detach a thread during execution like below code, Since "latch.countDown()" cannot be called, the thread remains waiting. So I want to use "latch.countDown()" and "Thread.currentThread().interrupt()" instead of "return", but I'm wondering if this is the correct way to do it. I'd like some help on what to do if I'm wrong.

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()
}

Upvotes: 1

Views: 89

Answers (1)

Turing85
Turing85

Reputation: 20195

If we use CountdownLatch::countDown and then want to wait until the latch releases, we would use CountdownLatch::await. I recommend reading the full documentation of CountdownLatch.

Calling Thread::interrupt on the current thread has no apparent effect since the thread is not blocking right now. It would have an effect if the thread was blocked, e.g. by an I/O operation. But then again, if the current thread is blocked, it cannot interrupt itself. It can be used to keep the state. See this question by Hesey and its answers for details.

If we use return, we return from the current method. This is a totally different construct than blocking.

Upvotes: 1

Related Questions