我可以使用python线程在一个python代码中运行两个类吗?

时间:2019-03-12 09:47:31

标签: python-3.x multithreading oop python-multithreading

我尝试使用此代码来了解python中的线程,但是我运行此代码时,它始终仅显示线程1详细信息。为什么呢?我该如何解决

听到的是代码

import threading
import time

class app1(threading.Thread):
    def server1():
        for i in range(100):
            print ("thread 1")
            time.sleep(1)

class app2(threading.Thread):
    def server2():
        for i in range(100):
            print ("thread 2")
            time.sleep(1)

t1 = app1.server1()
t2 = app2.server2()

t1.start()
t2.start()

1 个答案:

答案 0 :(得分:0)

您可以执行此操作,但是很遗憾,您使用的线程不正确。此版本可以使用。

import threading
import time

class app1(threading.Thread):
    def run(self):
        for i in range(100):
            print ("thread 1")
            time.sleep(1)

class app2(threading.Thread):
    def run(self):
        for i in range(100):
            print ("thread 2")
            time.sleep(1)

t1 = app1()
t2 = app2()

t1.start()
t2.start()

我确实向您推荐以下python mutithreading教程,例如:https://www.tutorialspoint.com/python3/python_multithreading.htm并阅读文档:https://docs.python.org/3/library/threading.html#module-threading