Java Wake Sleeping Thread

╄→尐↘猪︶ㄣ 提交于 2019-12-05 09:02:42

Thread.sleep throws InterruptedException if the thread is interrupted during the sleep. Catch that, and check your flag.

If the threads are sleeping with Thread.sleep(...), you can wake them up with Thread.interrupt(). Make sure you're handling the InterruptedException and testing Thread.currentThread().isInterrupted() in your loops.

You can call the interrupt() method on your thread and will make your Thread go to running state from block state, but it will throw an exception which is InterruptedException which by then you can shutdown your thread in the catch block

Also other solution is that you can use the Timer Task that will call the run method on a certain time you specified without putting your Thread to the block state

example:

public class TimerBomb {
  Toolkit toolkit;

  Timer timer;
  int count = 0;

  public TimerBomb(int seconds) {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000, seconds*1000);
  }

  class RemindTask extends TimerTask {
    public void run() {

        //do stuff here 

    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            new TimerBomb(5);


        }
    });
    t.start();
    System.out.println("Task scheduled.");
  }
}

It will run every 5 second forever.

You should look into ExecutorService and its shutdownNow() method (which generally interrupts all the active threads). You sense reinventing the scheduling wheel.

All of the other answers are good answers to the question that you actually asked, but none of them gives the best answer to the question that you should have asked. The question is, what's the best way to schedule several periodic tasks that must recur with different periods? The answer is, use a java.util.concurrent.ScheduledExecutorService.

Like all ExeuctorServices, it provides methods, shutdown() and shutdownNow(), for when you want the tasks to stop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!