Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What or who should interrupt a Thread?

According to Goetz in his book JCIP :

Because each thread has its own interruption policy , you should not interrupt a thread unless you know what interruption means to that thread .

Why did the Java language provide a public interrupt () method then ?Is this a design flaw? Who or what is supposed to interrupt a thread then ?

like image 634
Inquisitive Avatar asked Jul 13 '12 11:07

Inquisitive


3 Answers

What he means is that if you don't know what a thread does and how it works, you should not interrupt it. Since all threads can be interrupted, it is logical to have an interrupt() method in class Thread.

You could ask the same thing for many other methods that can do "harm" when executed at the wrong place. The methods are the tools, and the programmer must use these tools wisely in order to create a program that works correctly.

like image 153
vainolo Avatar answered Nov 15 '22 03:11

vainolo


I first recommend you to read Java Concurrency in Practice.

I think, this question can answer what you mentioned.

By the way, let's see how we can prevent threads. We can prevent a thread from execution by using any of the 3 methods of Thread class:

  1. yield()
  2. join()
  3. sleep()
  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

  2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.

  3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time.

like image 36
Lion Avatar answered Nov 15 '22 03:11

Lion


Well, its not a flaw, by no means. (However, other methods like Thread.stop() indeed are)

What makes Thread.interrupt()better is that it only affects the thread if it is blocked/waiting/sleeping. If it is running interrupt() only asks the thread to stop doing so by setting a status variable, which can be queried by Thread.interrupted() or Thread.isInterrupted()

Usually, it is the best way to let threads return from their run() method instead of stopping them externally in any way.

void run() {
    while(!isInterrupted())
        //executed

}

Be careful with Thread.interrupted() though, because it clears the interupt-status.

like image 22
TeaOverflow Avatar answered Nov 15 '22 05:11

TeaOverflow