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

can i run two classes in one python code using python threading?

我尝试使用此代码来了解 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()

您可以做到,但不幸的是您使用的线程不正确。这个版本可以。

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 多线程的教程,例如:https://www.tutorialspoint.com/python3/python_multithreading.htm and read the docs: https://docs.python.org/3/library/threading.html#module-threading