Python线程启动多个线程时的问题

时间:2014-10-31 18:06:53

标签: python linux multithreading

我想启动4个独立的线程,这些线程基本上是类的方法。 我在下面的代码中做错了什么:

from threading import Thread
import time
import random

class Creature:
    def __init__(self, name):
        self.name = name

    def melee(self, level):
        self.melee = level

    def shielding(self, level):
        self.shielding = level

    def health(self, total):
        self.health = total

    def attack(self, attacker, opponent):
        while 0 != 1:
            power = random.randint(1, attacker.melee)
            resistance = random.randint(1, opponent.shielding)
            resultant = power - resistance
            if resistance > 0:
                opponent.health -= resistance
                if opponent.health  < 0:
                    print(opponent.name, " is dead")
                    print("Opponent's health ", opponent.health)
                    quit()
                else:
                    print(attacker.name, " delivered an attack of ", resistance)
                    print("Opponent's health ", opponent.health)

    def healing(self, healed):
        while 0 != 1:
            if healed.health <= 0:
                if healed.health < 50:
                    life = random.randint(1, 50)
                    healed.health += life
                    if healed.health > 100:
                        healed.health = 100
                    print(healed.name, " has healed and now has a health of ", self.health)

Monster = Creature("Wasp")
Monster.health = 100
Monster.melee = 30
Monster.shielding = 15

Player = Creature("Knight")
Player.health = 100
Player.melee = 25
Player.shielding = 20

t1 = Thread(target=Player.attack(Monster, Player))
t1.start()
t2 = Thread(target=Monster.attack(Player, Monster),)
t2.start()
t3 = Thread(target=Player.healing(Player), args=())
t3.start()
t4 = Thread(target=Monster.healing(Monster), args=())
t4.start()

不知怎的,我做错了,因为只有t1开始了。 为什么程序只启动t1? : - (

谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码中的问题都可以在这一行中证明:

t1 = Thread(target=Player.attack(Monster, Player))

问题在于您调用 Player.attack,而不是将其传递给Thread构造函数。您的攻击方法永远不会返回,因此您永远不会尝试创建第一个Thread。你想做这样的事情:

t1 = Thread(target = Player.attack, args = (Monster, Player))