如何使用线程的id挂起线程? [英] how to suspend thread using thread's id?

查看:321
本文介绍了如何使用线程的id挂起线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试的代码

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

我们如何根据其ID暂停/暂停线程?
不推荐使用Thread.suspend,必须有一些替代方法来实现这一点。
我有线程ID我想暂停并终止线程。



编辑:我用过这个。

  AcQueryExecutor a = new AcQueryExecutor(thread_id_id); 
线程t1 =新线程(a);
t1.interrupt();
while(t1.isInterrupted()){
try {
Thread.sleep(1000);
} catch(InterruptedException e){
t1.interrupt();
返回;
}
}

但我无法阻止此线程。<这些天杀死线程的正确方法是 interrupt()它。这将 Thread.isInterrupted()设置为true并导致 wait() sleep( ),以及其他一些抛出 InterruptedException 的方法。



你的线程内部代码,您应该执行以下操作,检查以确保它没有被中断。

  //运行我们的线程虽然我们没有被中断
while(!Thread.currentThread()。isInterrupted()){
//做你的线程处理代码...
}

以下是如何在线程内处理中断异常的示例:

 试试{
Thread.sleep(...);
} catch(InterruptedException e){
//总是很好的做法因为捕获异常会清除标志
Thread.currentThread()。interrupt();
//如果我们被中断
return,我们很可能会停止该线程;
}

暂停线程的正确方法有点困难。您可以为它要注意的线程设置某种 volatile boolean suspended 标志。然后,您可以使用 wait() notify()来启动线程再次运行。


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.

解决方案

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 catching 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 then use wait() and notify() to start the thread running again.

这篇关于如何使用线程的id挂起线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆