如何使用线程的id挂起线程?
我正在尝试的代码
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; } }
但我无法阻止这个post。
这些天杀死线程的正确方法是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 ... }
这是一个如何处理线程内部中断exception的示例:
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; }
暂停线程的正确方法有点困难。 您可以为它要注意的线程设置某种volatile boolean suspended
标志。 然后,您可以使用wait()
和notify()
来重新启动线程。
我最近发布了一个内部使用ReadWriteLock
的PauseableThread实现。 使用其中一个或一个变体,你应该能够暂停你的线程。
至于通过id暂停它们,一个小小的谷歌搜索建议一种方法来迭代看起来应该工作的所有线程 。 Thread
已经暴露了一段时间的getId方法。
杀死线程是不同的。 @Gray整齐地覆盖了那一个。