What or who should abort Thread?

According to Goetz in his JCIP book:

Since each thread has its own interrupt policy, you should not interrupt a thread unless you know what interrupt means for that thread.

Why did the Java language provide a method public interrupt ()? Is this a design mistake? Who or what should interrupt the flow then?

+5
source share
3 answers

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

, " " . - , , , .

+4

Java Concurrency .

, question , .

, , . Thread:

  • yield()
  • join()
  • sleep()
  • yield() , . , , . , , , .

  • join() - t1 join() t2 i.e; t2.join() t1 , t2 .

  • sleep() .

+2

, , . ( , , Thread.stop() )

What makes Thread.interrupt()it better is that it only affects the thread if it is blocked / waiting / sleeping. If it works, it interrupt()just asks the thread to stop it by setting a status variable that can be requested with Thread.interrupted()orThread.isInterrupted()

This is usually the best way to allow threads to return from their method run(), rather than stopping them from outside in any way.

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

}

Be careful with Thread.interrupted(), though, since it clears interupt status.

+1
source

All Articles