示例示例Python中断线程的方法有两种:使用模块的Thread.join()方法。
Python中断线程的方法有两种:
1. 使用threading模块的Thread.join()方法。
Thread.join()方法可以让当前线程等待另一个线程执行完毕后再继续执行,而这个另一个线程就是调用join()方法的线程。
示例代码:
import threading
import time
def say_hello():
print("Hello")
time.sleep(2)
t = threading.Thread(target=say_hello)
t.start()
# 等待线程t执行完毕
t.join()
print("Done!")
2. 使用threading模块的Thread.setDaemon()方法。
Thread.setDaemon()方法可以将线程设置为守护线程,当主线程退出时,守护线程也会随之结束。
示例代码:
import threading
import time
def say_hello():
print("Hello")
time.sleep(2)
t = threading.Thread(target=say_hello)
# 设置为守护线程
t.setDaemon(True)
t.start()
# 主线程结束,守护线程也随之结束
print("Done!")
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(47条)