Python线程无法正常工作

时间:2017-05-30 05:23:47

标签: python multithreading python-multithreading

我跟随Bucky的Python tutorial,在他的线程视频中,他得到了这个输出(不完全是):

Send out messages
Send out messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Receive messages
Receive messages

但是当我尝试编写类似的代码时,我得到了这个输出:

Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...

这是我的代码:

# threading

import threading

class Messenger(threading.Thread):
    def run(self):
        for _ in range(10): # '_' is used when you want to run a for loop but don't care about the varialble
            print(threading.currentThread().getName())

x = Messenger(name='Sending messages...')
y = Messenger(name='Receiving messages...')

x.start()
y.start()

那么,我的代码是否有问题或者这里有什么问题以及为什么我的输出与Bucky的输出不同?

1 个答案:

答案 0 :(得分:0)

使用线程时无法保证输出顺序。执行线程的顺序取决于您的操作系统。我的系统输出完全不同。