Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...