在对多线程进行复习时,有个题目是一边听音乐一边看电影
故在网上找了教程对照着做,这是链接(13条消息) python 多线程 threading_tigerking1017的博客-CSDN博客
import threading
from time import sleep,ctime
def music(func):
for i in range(2):
print('我在听{}{}'.format(func, ctime()))
sleep(2)
def movie(func):
for i in range(2):
print('我在看{}{}'.format(func, ctime()))
sleep(5)
thrs = []
t1 = threading.Thread(target=music, args=('一生所爱'))
thrs.append(t1)
t2 = threading.Thread(target=movie, args=('敦刻尔克'))
thrs.append(t2)
if __name__ == '__main__':
for i in thrs:
i.start()
print('over', ctime())
这是代码,结果报错了
明明只有一个参数,它咋说我给了四个呢,遂将线程代码换成了
thrs = []
t1 = threading.Thread(target=music('一生所爱'))
thrs.append(t1)
t2 = threading.Thread(target=movie('敦刻尔克'))
thrs.append(t2)
代码成功运行,但是发现并没有多线程,仍然是单线程。
于是百度,发现都是细节,妥妥的细节,首先因为我的target加括号了,所以变成了单线程,然后再args=里面只有一个参数时, 应当加逗号,一下为正确代码
thrs = []
t1 = threading.Thread(target=music, args=('一生所爱',))
thrs.append(t1)
t2 = threading.Thread(target=movie, args=('敦刻尔克',))
thrs.append(t2)
程序成功运行
参考:
python多线程失败,一直只有一个线程的解决办法 - This_is_Y - 博客园 (cnblogs.com)