Thread.sleep vs Timers

给你一囗甜甜゛ 提交于 2019-12-14 03:33:17

问题


So in my research I have found these main differences between using a timer to execute an instruction and executing an instruction then making the thread sleep.

Observe the following code

public class StkFlow {
    public void event(ActionEvent e){
        //do some stuff
    }

    public static void main (String [] args){
        Timer tick=new Timer (200, event);
        tick.start ();
    }
}

AND

public class StkFlow {
    public static void main (String[] args){
    while (/*Condition*/){
        //Do some stuff
        Thread.sleep (200);
    }
}

The first piece of code uses a timer and executes some code every 200ms and the second piece of code executes some code and puts the thread to sleep for 200ms.The difference is that the timer already iterates for you and does not pause the thread unlike Thread.sleep which stops all processing,(the subject here is the timer) so what if you had a loop inside it, and what if this loop was comparing identical objects? Would it keep creating a new instance of this loop?, and if it does what is the end result, say, if it was processing some heavy duty instructions in that loop?

E.G

public class StkFlow {
    public void event(ActionEvent e){
        while (0==0){   
            //do some heavy duty stuff
        }
    }

    public static void main (String [] args){
        Timer tick=new Timer (200, event);
        tick.start ();
    }
}

回答1:


Thread.sleep which stops all processing, so what if you had a loop inside it, and what if this loop was comparing identical objects? Would it keep creating a new instance of this loop?, and if it does what is the end result, say, if it was processing some heavy duty instructions in that loop?

no, it won't, you need to start() a new thread. Thread.sleep() stops the current thread, but if you run it in its own thread then it will not stop the main thread and each task you may run in its own thread, tho they could start after the time ticks.



来源:https://stackoverflow.com/questions/32188643/thread-sleep-vs-timers

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