使用类创建的实例/对象的python多线程处理

2024-09-24 02:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试对多个实例使用线程

这是我的密码:

from threading import Thread
from random import randint
import time 


class MyThread(Thread):

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        for x in range(1,5):

            print(self.getName())
            time.sleep(2)

       mythread1 = MyThread()
       mythread2 = MyThread()

       mythread1.setName('Thread 1')
       mythread2.setName('Thread 2')

当我开始一个线程。输出将按预期显示

 mythread2.start()

Output: Thread 2

但如果我在另一个单元中运行第二个线程。早期单元格的输出出现在不同的单元格中

mythread1.start()

Output: Thread 1 Thread 2 Thread 1 Thread 2 Thread 1 Thread 2 Thread 1

我希望输出出现在每个单元格中。我认为多线程正在发生,但是输出出现在最后一个单元格中

我的过程中有什么问题吗?我需要让每个单元格打印出自己的输出

谢谢

enter image description here


Tags: 实例fromimportselfoutputtimeinitdef