如何杀死线程中运行的runnable?

ybzsozfc  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(424)

我上了一门课叫 AbortableThread 它应该在我想的时候开始和停止一个线程。类相对较小,因为它只包含以下代码:

  1. public class AbortableThread implements Runnable
  2. {
  3. private Thread worker;
  4. private Runnable target;
  5. public AbortableThread(Runnable target)
  6. {
  7. this.target = target;
  8. }
  9. public void start()
  10. {
  11. worker = new Thread(this);
  12. worker.start();
  13. }
  14. public void stop()
  15. {
  16. worker.interrupt();
  17. }
  18. public void run()
  19. {
  20. while (!worker.isInterrupted())
  21. target.run();
  22. }
  23. }

但是,打电话 stop() 不停止线程。我想那是因为 target.run() 在另一条线上运行,但我不知道。

ghhkc1vu

ghhkc1vu1#

尝试以下操作:

  1. public class AbortableThread implements Runnable
  2. {
  3. private final AtomicBoolean running = new AtomicBoolean(false);
  4. private Thread worker;
  5. private Runnable target;
  6. public AbortableThread(Runnable target)
  7. {
  8. this.target = target;
  9. }
  10. public void start()
  11. {
  12. worker = new Thread(this);
  13. worker.start();
  14. }
  15. public void stop()
  16. {
  17. running.set(false);
  18. }
  19. public void run()
  20. {
  21. running.set(true);
  22. while (running.get()) {
  23. try {
  24. // make an small sleep
  25. Thread.sleep(1);
  26. } catch (InterruptedException e){
  27. Thread.currentThread().interrupt();
  28. System.out.println(
  29. "Thread was interrupted, Failed to complete operation");
  30. }
  31. // do something here like the one in question; it must be none-blocking
  32. target.run();
  33. }
  34. }
  35. }

一个完整的例子可以在这里找到:
如何杀死java线程

展开查看全部
3vpjnl9f

3vpjnl9f2#

没有一个好的方法从外部阻止runnable(作为最后的手段,有stop,但这不是一个好方法)。runnable需要是一个好公民,并使用thread.currentthread().isinterrupted()检查中断本身。如果runnable捕捉到interruptedexception,中断标志将被清除;runnable需要通过调用当前线程上的中断来恢复中断标志。
在发布的代码中,发生的情况是runnable在工作线程上执行,工作线程在runnable完成之前没有机会检查中断标志。假设runnable是

  1. () -> { try {
  2. Thread.sleep(100000L):
  3. } catch (InterruptedException e) {}}

然后,当worker被中断时,睡眠将被缩短,但是中断标志将被清除,这样runnable将在循环的下一次迭代中再次执行。

相关问题