我试图用python编写一个警报,它有6个需要多线程处理的函数。其中5个是警报,其中一个显示时间。每当选择菜单选项和警报响起时,线程都需要启动和停止。显示线程是唯一一个一直运行到程序停止的线程。我当前的报警代码如下所示(为了清晰起见,我删除了很多代码)
class TAlarm1 (threading.Thread):
def Alarm1():
while True:
#code which keeps running until the time is equal to the input given (expected to thread)
thread1 = threading.Thread(target=TAlarm1)
thread1.start()
def AlarmSelector():
print("Select an Alarm") #5 alarms will be added however each one accomplishes the same task. all of them need to run simultaneously
choice = int(input())
if choice == 1:
ala = TAlarm1()
ala.Alarm1()
if choice == 6:
DisplayTime() #goes back to displaying time
每当我运行此代码时,程序都不会显示任何错误,但它不会在TAlarm1()中运行代码。 我怎样才能解决这个问题
在Python中实现线程代码有两种基本方法。你似乎每个都有一半
第一个实现模型是将要在线程中运行的逻辑放入函数中,然后在创建
threading.Thread
实例时将该函数作为target
参数传递:另一种实现方法是将
threading.Thread
子类化,并将要运行的代码放在run
方法(或从run
调用的其他方法)内的线程中。如果您的线程代码具有某些复杂的状态,并且希望在线程运行时能够使用其他方法来操纵该状态,则这一点尤其有用:虽然我不清楚你的意图。下面是如何在线程的run方法被覆盖的情况下对其进行子类化,并有条件地启动它
线程只能启动一次,因此每次需要运行时都必须创建一个新线程
Thread
的target
参数采用可调用的。类是可调用的,但调用它只会创建类的实例。改为传递一个函数:相关问题 更多 >
编程相关推荐