daemonimport threading
def work(num):
for i in range(num):
print(threading.current_thread().name " " str(i))
t = threading.Thread(target=work, args=(10,), name='守护线程')
#t.daemon = True
t.start()
for i in range(10):
pass
localimport threading
import time
# 不使用 threading.local
num = 0
def work():
global num
for i in range(10):
num = 1
print(threading.current_thread().getName(), num)
time.sleep(0.0001)
for i in range(5):
threading.Thread(target=work).start()
# 使用 threading.local
num = threading.local()
def work():
num.x = 0
for i in range(10):
num.x = 1
print(threading.current_thread().getName(), num.x)
time.sleep(0.0001)
for i in range(5):
threading.Thread(target=work).start()
timer
代码语言:python代码运行次数:0复制
from threading import Timer
import time
#定时器-单次执行
# def work():
# print("Hello Python")
# # 5 秒后执行 work 方法
# t = Timer(5, work)
# t.start()
#定时器-重复执行
count = 0
def work():
print('当前时间:', time.strftime('%Y-%m-%d %H:%M:%S'))
global t, count
count = 1
# 如果 count 小于 5,开始下一次调度
if count < 5:
t = Timer(1, work)
t.start()
# 指定 2 秒后执行 work 方法
t = Timer(2, work)
t.start()