我正在尝试启动多个线程,下一个线程的开始时间将取决于它在第一个线程等中发生的情况。
因此,我在Stackoverflow中找到了类似他在谈到Event类时的回答: Python threading - How to repeatedly execute a function in a separate thread?
所以我尝试用这种方式:
from threading import Thread, Event
import time
class MyThread3(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while self.stopped.wait(0.5):
print("The Third thread is running..")
class MyThread2(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
time.sleep(1)
my_event2.clear()
time.sleep(3)
my_event.set()
time.sleep(2)
my_event2.set()
class MyThread1(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(0.5):
print("Thread is running..")
my_event = Event()
my_event2 = Event()
thread1 = MyThread1(my_event)
thread2 = MyThread2(my_event)
thread3 = MyThread3(my_event2)
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
如果我不在Thread3中放东西,它与Thread1同时开始,那为什么我放相反的东西,如果Event的状态改变了而它又没有开始呢? 我们不能在线程内更改事件吗? 如何从另一个线程开始一个线程?
答案 0 :(得分:0)
哼,你是对的,我什至没有想到。
有我找到的解决方案:
import time
from threading import Thread, Event
class MyThread1(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
x = 0
while not self.stopped.wait(0.5):
if x == 5:
thread2.start()
print("Thread 1 is running..")
x += 1
class MyThread2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print("Procces 2 start and the process 1 will stop in 2 seconds")
x = 0
while x < 10:
if x == 5:
my_event.set()
print("x = ",x)
time.sleep(0.5)
x += 1
my_event = Event()
thread1 = MyThread1(my_event)
thread2 = MyThread2()
thread1.start()
我发现的解决方案似乎不太好,还有其他建议使用干净的代码吗?
关于这种多线程,我还有另一个问题,我们如何才能在线程中使用变量在另一个线程中使用它?
例如:
线程1正在运行 线程2正在运行
线程1正在等待10分钟,并将检查变量Default 线程2计算内容并将变量Default更改为20
在等待线程1 10分钟后,看到Default的值为20并执行任务,否则他将结束。