Skip to main content
 首页 » 编程设计

python之在 Python 中重用线程

2025年02月15日7lhb25

我正在尝试为文字游戏编写一个实时战斗系统。我希望玩家能够行动并且必须等待一定的秒数才能再次行动,而 NPC 也在做同样的事情。

我写了一个小例子:

import threading 
import time 
 
def playerattack(): 
    print("You attack!") 
    time.sleep(2) 
 
 
def npcattack(): 
    while hostile == True: 
        print("The enemy attacks!") 
        time.sleep(3) 
 
p = threading.Thread(target=playerattack) 
n = threading.Thread(target=npcattack) 
 
hostile = False 
 
while True: 
    if hostile == True: 
        n.start() 
    com = input("enter 'attack' to attack:") 
    if 'attack' in com: 
        hostile = True 
        p.start() 

该示例对于第一次攻击将正常工作: 我输入“攻击”,敌对标志设置为 True,npc 攻击线程启动,但当我再次尝试攻击时出现“RuntimeError:线程只能启动一次”。

有没有办法在不抛出错误的情况下重用该线程?还是我做错了?

请您参考如下方法:

问题是该线程已经在运行,并且您无法再次启动正在运行的线程,因为 while 循环再次调用 n.start()。

即使线程死了,您也需要重新初始化线程实例并重新启动。您不能启动旧实例。

在你的情况下,在 while True 循环中,它试图多次启动一个线程。你要做的是检查线程是否正在运行,如果没有运行则启动线程实例。

import threading 
import time 
 
def playerattack(): 
    print("You attack!") 
    time.sleep(2) 
 
 
def npcattack(): 
    while hostile: 
        print("The enemy attacks!") 
        time.sleep(3) 
 
p = threading.Thread(target=playerattack) 
n = threading.Thread(target=npcattack) 
 
hostile = False 
 
while True: 
    if hostile and not n.is_alive(): 
        try: 
            n.start() 
        except RuntimeError: #occurs if thread is dead 
            n = threading.Thread(target=npcattack) #create new instance if thread is dead 
            n.start() #start thread 
 
    com = input("enter 'attack' to attack:") 
 
    if 'attack' in com: 
        hostile = True 
        if not p.is_alive(): 
            try: 
                p.start() 
            except RuntimeError: #occurs if thread is dead 
                p = threading.Thread(target=playerattack) #create new instance if thread is dead 
                p.start()