我是Python新手。这是我的代码:如何正确停止python线程?
import logging
logging.basicConfig(level = logging.DEBUG, format = "[%(levelname)s] (%(threadName)-10s) %(message)s")
import threading
import time
def thread1():
for i in range(0, 10, 2):
logging.debug(i)
time.sleep(1)
def thread2():
for i in range(10, 20):
logging.debug(i)
time.sleep(1)
t1 = threading.Thread(name = "thread1", target = thread1)
t1.setDaemon(True)
t1.start()
t2 = threading.Thread(name = "thread2", target = thread2)
t2.setDaemon(True)
t2.start()
当我复制的代码,并粘贴成一个Python的命令行提示符下,我得到了以下的结果。
正如你所看到的,2个线程已经完成,但似乎该程序不会退出(我没有得到命令提示符后面)。我认为它与我的代码没有属性结束线程有关。真的吗?如何解决这个问题? 谢谢。
请参阅我的问题的回答[如何启动和停止线程](http://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread/15734837 #15734837)。 – martineau
afaik您只需要在您的主程序中调用'thread_1.join()' –
thread.setDaemon()已被弃用,请使用thread.daemon = True(或在创建线程时将其作为关键字arg传递)。请参阅文档:http://docs.python.org/2/library/threading.html#threading.Thread.daemon – ThinkChaos