我想在Python中同时在一个类的方法内运行2个函数。我试图使用threading
模块,但它不起作用。我的例子代码如下:在类Python的一个方法内部执行两个函数
import os, sys
import threading
from threading import Thread
class Example():
def __init__(self):
self.method_1()
def method_1(self):
def run(self):
threading.Thread(target = function_a(self)).start()
threading.Thread(target = function_b(self)).start()
def function_a(self):
for i in range(10):
print (1)
def function_b(self):
for i in range(10):
print (2)
run(self)
Example()
如果上面的代码得到执行,它将只打印所有1
第一个,然后将所有2
秒。但是,我想要的是同时打印1
和2
。因此,期望的输出应该是混合起来的。
是threading
模块能够做到这一点吗?如果不是,哪个模块可以做到这一点?如果有人知道如何解决它,请让我知道。感谢!
我不认为这回答了这个问题,因为这个问题是关于一个类中做的一切而不是将组件写出来或创建新的类。 – Hannu
看起来你有一个点,我会尽量正确地修改它。 –