Ágota Horváth
Ágota Horváth

Reputation: 1353

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?

Upvotes: 20

Views: 56427

Answers (6)

Paul Okeke
Paul Okeke

Reputation: 1414

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.

Upvotes: 3

Sage
Sage

Reputation: 15418

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.

Upvotes: 3

John Vint
John Vint

Reputation: 40256

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

Upvotes: 6

chasep255
chasep255

Reputation: 12175

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.

Upvotes: 27

csn
csn

Reputation: 386

interrupt() method does not stop the Thread. read this for more detailed explanation http://www.ibm.com/developerworks/java/library/j-jtp05236/

Upvotes: 0

brunch875
brunch875

Reputation: 869

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.

Upvotes: 5

Related Questions