代码之家  ›  专栏  ›  技术社区  ›  Yoda ESG

如果睡眠被打断的线程被唤醒,它是否应该重新自我干扰?

  •  2
  • Yoda ESG  · 技术社区  · 3 年前

    public void run() {
        while (!Thread.interrupted()) {
            //A TASK HERE
            try {
                Thread.sleep((long) (500 + Math.random() * 100));
            } catch (InterruptedException e) {
                interrupt(); //it was interrupted while it was sleeping
            }
        }
    }
    

    其目的是通过中断线程来终止线程。我能像以前那样重新中断自己吗?还是我应该设置一个标志 stop = true 在例外条款内?

    1 回复  |  直到 3 年前
        1
  •  4
  •   Andy Turner    3 年前

    捕捉循环外的中断:

    public void run() {
        try {
            while (true) {
                //A TASK HERE
                Thread.sleep((long) (500 + Math.random() * 100));
            }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
    }
    

    InterruptedException ,如果没有,最好重新中断当前线程 真正地 处理好了,你不能简单地把 中断异常 (例如,因为它在一个没有声明抛出 中断异常 Exception Throwable ).

    这允许 run() 他们 也能阻止他们的行为。