multithreading - Java Thread.stop() vs Thread.interrupt()

ID : 274398

viewed : 10

Tags : javamultithreadingjava





Top 5 Answer for multithreading - Java Thread.stop() vs Thread.interrupt()

vote vote

94

When you call interrupt() it triggers a boolean flag which tells the run function it should stop. That is why I usually write my run functions like this.

void run() {     while(!Thread.interrupted())     {         //Do something     } } 

Just because you call interrupt doesn't mean the thread will stop immediately or at all. It depends on what is in the run function.

vote vote

88

To really push the point why you shouldnt use Thread.stop()?

Doug Lea recently mentioned that Thread.stop will be the first de-implemented method for Java come Java 8.

His response to this comment from someone:

Also, one other thing synchronized has going for it is it handles async aborts of threads (I.e. thread.stop()). I know stop() is deprecated and all, but you never know.

Was:

But you do know! As of JDK8, Thread.stop is really gone. It is the first deprecated method to have actually been de-implemented. It now just throws UnsupportedOperationException.

http://cs.oswego.edu/pipermail/concurrency-interest/2013-December/012028.html

vote vote

78

You should take a look at this article: http://10kloc.wordpress.com/2013/03/03/java-multithreading-steeplechase-stopping-threads/

Basically you shouldn't STOP a thread (unsafe), but interrupt it. What you're missing is making the thread handle the interruption.

vote vote

62

renderThread.interrupt() does not interrupt the thread, it continues to run.

  • If the thread is executing and interrupt() is invoked it's interrupt status is set.
  • If this thread is blocked in an invocation one of wait methods of the Object class, or of the Thread.join and Thread.sleep methods of this class then its interrupt status will be cleared and it will receive an InterruptedException.

For example:

Thread t = new Thread()       {           public void run()           {               try {                   for(int i=0; i<10000;i++)                       System.out.println("Is interrupTed? "+this.isInterrupted());                    Thread.sleep(200);               } catch (InterruptedException ex) {                   Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);               }            }       };       t.start();       t.interrupt();     } 

The above code, I have used a for loop to intercept the interrput flag with isInterrupted() function and printed it. As t.interrupt() is invoked, isInterrupted() will return true which you will see in the console. As soon as it reaches the Thread.sleep(miliTime) you will see that InterruptedException is caught which was thrown as described above.

Stopping a thread:

you could make use of this isInterrupted() flag check if an interrupt() was invoked on it and return from the execution:

For example:

Thread t = new Thread()       {           public void run()           {               long executeTime = System.currentTimeMillis() ;               int i = 0;                   for(; i<10000 && !this.isInterrupted();i++)                       System.out.println("Is interrupted? "+this.isInterrupted());                 System.out.println("Was Interrupted? "+this.isInterrupted()                                   +" after cycle: "+ i);                System.out.println("Time it gets Executed: "                                   +(System.currentTimeMillis() - executeTime+" ms"));            }       };       t.start();         try {             Thread.sleep(200);         } catch (InterruptedException ex) {             ex.printStackTrace();         }       t.interrupt(); 

While running the above code: i have sent the main thread to sleep for 200 inside the static main function to allow the started thread t to run for some time. Then i invoked
t.interrupt() on it which causes the for loop to stop and print a output as following:

Was Interrupted? true after cycle: 1477 Time it gets Executed: 258 ms 

Which indicates that the for loop has 1148 iteration before t.interrupt(); was invoked in the main function.

Please read the documentation of Thread.interrupt() function for more details.

vote vote

55

All You need do to interrupt the current thread or terminate the running process of the thread is to add the below statement within you catch block

try {    Thread.sleep(4000);    System.out.println("VAS CONSULTING") } catch(InterruptedException e) {    //Stop printing out VAS CONSULTING    return;  /*This will terminate the thread*/ } 

also if a method that doesn't throw an Interrupted Exception isn't used within the run method you can do this to handle Thread Interruption or terminate the Thread

@Override public void run() {     System.out.println("VAS CONSULTING");    if(Thread.Interrupted())    {      doSomethingElse();//process something else within the thread     return; //Terminates the current Thread    }  } 

I hope this Helps You or Someone Else.

Top 3 video Explaining multithreading - Java Thread.stop() vs Thread.interrupt()







Related QUESTION?