MoRabbit 2022-12-18 21:06 采纳率: 95.5%
浏览 27
已结题

python 线程如何多次调用?

t1 怎么可以多次调用呢?

import time
import threading

def end():
    time.sleep(2)
    print('完成')

t1 = threading.Thread(target=end)

def start():
    print('开始')
    for i in range(5):
        for r in range(5):
            time.sleep(1)
            print(r)
        t1.start()

start()
运行结果及详细报错内容
开始
0
1
2
3
4
0
完成
1
2
3
4
Traceback (most recent call last):
  File "D:\Code\NewWorld\Test1.py", line 18, in <module>
    start()
  File "D:\Code\NewWorld\Test1.py", line 16, in start
    t1.start()
  File "C:\Users\XXX\AppData\Local\Programs\Python\Python310\lib\threading.py", line 923, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once

  • 写回答

1条回答 默认 最新

  • ShowMeAI 2022-12-18 21:13
    关注

    望采纳,可以这样改

    import time
    import threading
     
    def end():
        time.sleep(2)
        print('完成')
     
    def start():
        print('开始')
        for i in range(5):
            t1 = threading.Thread(target=end)
            for r in range(5):
                time.sleep(1)
                print(r)
            t1.start()
     
    start()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月26日
  • 已采纳回答 12月18日
  • 创建了问题 12月18日