【问题标题】:can i run two classes in one python code using python threading?我可以使用 python 线程在一个 python 代码中运行两个类吗?
【发布时间】:2019-03-12 09:47:30
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以这样做,但不幸的是您错误地使用了线程。这个版本可以用。

    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 并阅读文档:https://docs.python.org/3/library/threading.html#module-threading

    【讨论】:

    猜你喜欢
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多