在Python中重用线程

2024-09-28 05:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个文本游戏的实时战斗系统。我希望玩家能够表演,并且在他们能够再次表演之前必须等待一定的秒数,而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()

对于第一次攻击,该示例效果良好: 我输入'attack',敌方标志设置为True,npc攻击线程启动,但是当我再次尝试攻击时,我得到一个“RuntimeError:线程只能启动一次”。在

有没有一种方法可以在不引发错误的情况下重用该线程?还是我做错了?在


Tags: importtruetargettimedefsleep线程thread
2条回答

我们用start()方法启动线程。 之后我们使用run()方法,即p.run()和{},而不是{}和{}来重用相同的线程。在

问题是线程已经在运行,并且由于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()

相关问题 更多 >

    热门问题