【问题标题】:How to suspend thread using thread's id?如何使用线程的 id 挂起线程?
【发布时间】:2012-06-13 17:16:29
【问题描述】:

我正在尝试的代码

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

我们如何根据线程的 id 挂起/暂停线程? Thread.suspend 已被弃用,必须有一些替代方案来实现这一点。 我有线程 ID,我想挂起并终止线程。

编辑:我用过这个。

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; 
    } 
} 

但我无法停止此线程。

【问题讨论】:

  • 哦,我明白了,您添加了一个问题。您没有将 isInterrupted() 检查放在主线程中。你把它放在AcQueryExecutor 代码里面。 AcQueryExecutor 线程应该检查它自己的线程(本身)是否已被中断。调用者中的 while 循环永远不应运行,因为在您刚刚调用 t1.interrupt() 之后,t1.interrupted() 将始终为真。
  • 我已经编辑了我的答案以使其更清楚。很抱歉造成混乱。

标签: java multithreading


【解决方案1】:

我们如何根据线程的 id 挂起/暂停线程? ...我有线程 ID,我想暂停并终止线程。

这些天杀死线程的正确方法是interrupt()它。这会将Thread.isInterrupted() 设置为true,并导致wait()sleep() 和其他几种方法抛出InterruptedException

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

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

下面是一个如何处理线程内部中断异常的示例:

 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;
 }

暂停线程的正确方法有点困难。您可以为它会关注的线程设置某种volatile boolean suspended 标志。您也可以使用object.wait() 挂起一个线程,然后使用object.notify() 重新启动它运行。

【讨论】:

  • 执行神经进入上述区块。我添加了这个 AcQueryExecutor a=new AcQueryExecutor(thread_id_id);线程 t1 = 新线程(a); t1.interrupt(); while (t1.isInterrupted()) { 尝试 { Thread.sleep(1000); } catch (InterruptedException e) { t1.interrupt();返回; } }
  • 我不太明白@happy。你开始线程了吗?如果线程已启动并已被中断,则该代码将起作用。
  • @happy not(!) 运算符在 while 循环中丢失,现在已更正。
  • 谢谢!格雷,这是一个很好的答案!
  • 非常感谢。正在寻找这种功能。一个问题是,是否存在任何内存泄漏,因为该线程实际上没有被杀死。我还能做些什么来彻底杀死那个线程??
【解决方案2】:

我最近发布了一个PauseableThread 实现,它在内部使用了ReadWriteLock。使用其中一种或变体,您应该能够暂停线程。

至于通过 id 暂停它们,一点谷歌搜索建议 a way to iterate over all threads 看起来应该可以工作。 Thread 暴露了 getId 方法已有一段时间了。

杀死线程是不同的。 @Gray 已经巧妙地覆盖了那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多