Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following code:

renderThread = new Thread(new Runnable() {

    @Override
    public void run() {
        for (int i = 0; i < 10000000; i++) {
            System.out.println("Number: " + i);
        }
    }
});

renderThread.start();

try {
    Thread.sleep(100);
} catch (InterruptedException ex) {
    ex.printStackTrace();
}

renderThread.interrupt(); //It should stop, but it does not stop.

renderThread.interrupt() does not interrupt the thread, it continues to run. If I replace renderThread.interrupt() with .stop(), then the thread stops. However, .stop() is deprecated. Then, what is the proper way of stopping a thread, if stop is deprecated and interrupt does not work?

like image 739
Ágota Horváth Avatar asked Dec 11 '13 19:12

Ágota Horváth


People also ask

Why was the stop () method on thread deprecated?

stop is being deprecated because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.)

Does interrupt stop a thread in Java?

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

Does interrupt stop a thread?

interrupt() is called, it sets a flag known as the interrupt status to true. This means that the thread has to stop performing further execution.

What does interrupt () do in Java?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.


5 Answers

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.

like image 175
chasep255 Avatar answered Oct 16 '22 22:10

chasep255


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

like image 26
John Vint Avatar answered Oct 16 '22 22:10

John Vint


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.

like image 42
brunch875 Avatar answered Oct 16 '22 22:10

brunch875


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.

like image 39
Sage Avatar answered Oct 16 '22 21:10

Sage


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.

like image 41
Paul Okeke Avatar answered Oct 16 '22 21:10

Paul Okeke