Waking up a sleeping thread - interrupt() versus “splitting” the sleep into multiple sleeps

前端 未结 4 673
温柔的废话
温柔的废话 2021-02-10 10:40

This requirement came up in my Android app, but it applies to Java in general. My app \"does something\" every few seconds. I have implemented this as follows (just relevant sni

4条回答
  •  眼角桃花
    2021-02-10 10:46

    This answer helped me do the job. Posting some code on how I achieved it. Of particular importance are startTask() and setInterval().

    public class PeriodicTask {
    
        private volatile boolean running = true;
        private volatile int interval = 5;
        private final Object lockObj = new Object();
    
        public void startTask() {
            while (running) {
                doSomething();
                synchronized (lockObj) {
                    try{
                        lockObj.wait(interval * 1000);
                    } catch(InterruptedException e){
                        //Handle Exception
                    }
                }
            }
        }
    
        public void stopTask() {
            this.running = false;
        }
    
        public void setInterval(int newInterval) {
            synchronized (lockObj) {
                this.interval = newInterval;
                lockObj.notify();
            }
        }
    }
    

提交回复
热议问题