【发布时间】:2019-01-03 18:33:09
【问题描述】:
我正在尝试启动多个线程,下一个线程的启动时间将取决于它会在第一个等中发生的情况。
所以我在 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 同时启动,那么为什么如果我放置了相反的位置并且事件的状态发生了变化并且它没有启动呢? 我们不能更改线程内的事件? 如何从另一个线程启动一个线程?
【问题讨论】:
-
“启动线程”是什么意思?通常的意思是
.start方法启动线程。另请注意,您对线程 3 使用私有my_event2,(其他两个线程都使用my_event)。所以你几乎无法控制其他线程的thread3执行。
标签: multithreading events