Java Wake Sleeping Thread

笑着哭i 提交于 2019-12-22 05:55:47

问题


I did some reading of other post but didn't find an exact answer to what I'm looking for, so I hope someone can give some some clarification.

I have a program that will run for some time. I have some threads that run in the back ground that perform various tasks, to keep things simple let think of 3 threads. ThreadA performs a task every 10 seconds, where ThreadB does something every 30 seconds and ThreadC does something every 5 mintues.

I don't use busy waiting, and put the threads to sleep for the designated times.

My question is regarding a clean shut down. I have a variable that each of the threads have read access too, so they can see when the user initiates the exit of the program. The next time the threads are active, they exit their loops and join and all is good. But you can see that ThreadC only wakes up every 5 minutes.

The question I have is can I signal the sleeping threads to wake up and exit before their sleep time is over? If this is not possible, do I need to rework the code to use wait() and notify() or is there a better way?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/24111441/java-wake-sleeping-thread

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