我正在尝试的代码
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;
}
}
但是我无法阻止这个线程。
我们如何根据线程的 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()
重新启动它运行。 实现,它在内部使用了 ReadWriteLock
。使用其中之一或变体,您应该能够暂停您的线程。
至于通过 id 暂停它们,稍微谷歌搜索一下就建议了一种迭代所有线程的方法
,看起来应该可行。 Thread
已经公开了
getId方法一段时间了。 杀死线程是不同的。 @Gray