Python,线程在使用线程锁时以随机顺序开始

Kex*_*Kex 4 python multithreading

这里真的是Python的新手,并试图让我的头脑绕线程.我有代码:

import threading, time

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        super(myThread, self).__init__()
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting ", self.name
        threadLock.acquire()
        print_time(self.name , self.counter, 3)
        #Free the lock to release the next thread
        print "%s released, ready for the next thread"%self.name
        threadLock.release()

class sillyThread(threading.Thread):
    def run(self):
        threadLock.acquire()
        print "silly silly!"
        time.sleep(2)
        print "Silly silly!"
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s"%(threadName, time.ctime())
        counter -= 1


threadLock = threading.Lock() 
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread3 = sillyThread()

thread1.start()
thread2.start()
thread3.start()


threads.append(thread1)
threads.append(thread2)
threads.append(thread3)

# Wait for all threads to complete
for t in threads:
    t.join()
    print "%s is finished"%t.name
print "Exiting Main Thread"
Run Code Online (Sandbox Code Playgroud)

我希望线程1首先启动,线程2和线程3放在块上,直到线程1完成.所以执行的顺序是线程1,线程2和线程3.但是每次运行代码时它都会有所不同.例如,有时Thread-3将首先运行,因为我先调用该行thread1.start()并且之后应该被锁定,因此没有意义.有人可以给我一些指示,说明为什么会这样吗?

And*_*ndy 6

Thread.start只是安排一个线程开始.它实际上并没有在那时开始.相反,从那时起,操作系统将接管并启动线程,因为它看起来与您的主线程异步.

如果您确实想要同步线程的运行,则需要使用互斥或​​其他同步原语来自行完成.