Timer和Thread有什么区别? Python,线程化

时间:2016-12-23 17:17:29

标签: python multithreading python-3.x python-multithreading

TextView textView = (TextView) signInButton.getChildAt(0); textView.setText("your_text_xyz"); threading.Timer之间有什么区别?

当我使用Timer函数时,它会在具有延迟的单独线程中启动目标命令。

当我使用Thread函数时,它会在单独的线程中使用args启动目标命令。

我认为它是一样的,不是吗?

2 个答案:

答案 0 :(得分:4)

值得一看的是实施。

# _Timer is thinly wrapped by Timer; excluding that wrapper for terseness
class _Timer(Thread):
    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=[], kwargs={})
            t.start()
            t.cancel()     # stop the timer's action if it's still waiting

    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

因此,是的,Timer只是一个Thread的实例,它在给定的延迟后调用你的函数,使用Event机制进行有效的调度,并提供一个cancel(),可靠地阻止函数被如果延迟尚未到期,则完全打电话。

如上所述,Thread是执行繁重工作的实现,而Timer是一个增加额外功能的助手(前端延迟);如果Timer(0, func)不存在,Thread将无效。

作为对象的Thread提供了比 能够覆盖要调用的函数更多的灵活性,而没有该函数可以访问实例变量 - 请查看{{1本身,以及它如何使用该功能来添加和尊重Timer。如果没有子类cancel(),你就不能在Timer之上做到这一点,{顾名思义)这是一个不承诺在未来版本中保持稳定的实现细节。

因此,_Timer具有更多的移动部分,并且不如Timer()更灵活 - 这两者都是软件工程中固有的缺点 - 但对于特定的中等常见用例而言非常方便。为什么一个同时提供这两个?

答案 1 :(得分:0)

你已经解释了差异。 Thread()是一个线程,Thread是一个线程,其执行至少延迟指定的时间。

https://docs.python.org/2/library/threading.html#timer-objects

相关问题