Multithreading Python如何在另一个线程中启动线程?
我正在尝试启动多个线程,下一个线程的启动时间将取决于第一个线程将发生什么,等等 因此,我在Stackoverflow中找到了一些帖子,比如他在回答中提到的事件类: 所以我试着这样做:Multithreading Python如何在另一个线程中启动线程?,multithreading,events,Multithreading,Events,我正在尝试启动多个线程,下一个线程的启动时间将取决于第一个线程将发生什么,等等 因此,我在Stackoverflow中找到了一些帖子,比如他在回答中提到的事件类: 所以我试着这样做: from threading import Thread, Event import time class MyThread3(Thread): def __init__(self, event): Thread.__init__(self) self.stopped =
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()
如果我将while不放在Thread3中,它将与Thread1同时启动,那么如果我将while放在Thread3中,并且如果事件的状态发生变化而它不启动,那么为什么呢?
我们无法更改线程内的事件?
我怎样才能从另一个线程开始一个线程呢?嗯,这是真的,你说得对,我甚至没想过 我找到了一个解决方案:
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()
导入时间
从线程导入线程,事件
类MyThread1(线程):
定义初始化(自我,事件):
线程。\uuuu初始化\uuuuu(自)
self.stopped=事件
def运行(自):
x=0
而不是自我。已停止。等待(0.5):
如果x==5:
thread2.start()
打印(“线程1正在运行…”
x+=1
类MyThread2(线程):
定义初始化(自):
线程。\uuuu初始化\uuuuu(自)
def运行(自):
打印(“进程2启动,进程1将在2秒内停止”)
x=0
当x<10时:
如果x==5:
my_event.set()
打印(“x=”,x)
睡眠时间(0.5)
x+=1
my_event=event()
thread1=MyThread1(my_事件)
thread2=MyThread2()
thread1.start()
我发现的解决方案似乎不是很好,有没有其他建议可以使用干净的代码
我还有一个关于这种多线程的问题,我们如何在一个线程中使用一个变量来在另一个线程中使用它
例如:
线程1正在运行
线程2正在运行
线程1正在等待10分钟,并将检查变量默认值
线程2计算一些东西并将变量Default更改为20
线程1等待10分钟后,请查看默认值为20并执行任务,否则他将结束。您所说的“启动线程”是什么意思?通常的意思是.start
方法启动线程。另外请注意,您对thread3使用privatemy_event 2
(其他两个线程都使用my_event
)。因此,您很难从其他线程控制thread3的执行。