Thread.sleep vs计时器 [英] Thread.sleep vs Timers

查看:96
本文介绍了Thread.sleep vs计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的研究中,我发现使用计时器执行指令与执行指令然后使线程进入睡眠状态之间存在这些主要区别.

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.

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);
    }
}

第一段代码使用计时器并每200ms执行一次代码,第二段代码执行一些代码并使线程进入睡眠状态200ms.不同之处在于计时器已经为您进行了迭代并且不会暂停与Thread.sleep不同的是,该线程会停止所有处理(这里的主题是计时器),所以如果其中有一个循环,并且该循环在比较相同的对象,该怎么办?它会继续创建该循环的新实例吗?如果执行了最终结果,例如,是否正在处理该循环中的一些重型指令?

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

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 ();
    }
}

推荐答案

Thread.sleep会停止所有处理,因此,如果其中有一个循环,又该循环是否比较相同的对象,该怎么办?它会继续创建该循环的新实例吗?如果执行了最终结果,例如,是否正在处理该循环中的一些重型指令?

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?

不,不会,您需要start()一个新线程. Thread.sleep()停止当前线程,但是如果您在其自己的线程中运行它,则它不会停止主线程,并且每个任务都可以在其自己的线程中运行,因为它们可以在时间滴答之后开始.

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.

这篇关于Thread.sleep vs计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆