问题
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