Search code examples
javamultithreading

How to suspend thread using thread's id?


Code which I am trying

public void killJob(String thread_id) throws RemoteException {
    Thread t1 = new Thread(a);
    t1.suspend();
}

How can we suspend/pause thread based on its id? Thread.suspend is deprecated,There must be some alternative to achieve this. I have thread id I want to suspend and kill the thread.

Edit: I used this.

AcQueryExecutor a = new AcQueryExecutor(thread_id_id);
Thread t1 = new Thread(a); 
t1.interrupt(); 
while (t1.isInterrupted()) { 
    try { 
       Thread.sleep(1000); 
    } catch (InterruptedException e) { 
       t1.interrupt(); 
       return; 
    } 
} 

But I am not able to stop this thread.


Solution

  • How can we suspend/pause thread based on its id? ... I have thread id I want to suspend and kill the thread.

    The right way to kill a thread these days is to interrupt() it. That sets the Thread.isInterrupted() to true and causes wait(), sleep(), and a couple other methods to throw InterruptedException.

    Inside of your thread code, you should be doing something like the following which checks to make sure that it has not been interrupted.

     // run our thread while we have not been interrupted
     while (!Thread.currentThread().isInterrupted()) {
         // do your thread processing code ...
     }
    

    Here's an example of how to handle interrupted exception inside of a thread:

     try {
         Thread.sleep(...);
     } catch (InterruptedException e) {
         // always good practice because throwing the exception clears the flag
         Thread.currentThread().interrupt();
         // most likely we should stop the thread if we are interrupted
         return;
     }
    

    The right way to suspend a thread is a bit harder. You could set some sort of volatile boolean suspended flag for the thread that it would pay attention to. You could also use object.wait() to suspend a thread and then object.notify() to start it running again.