为什么我的线程锁不能正常工作?

Why aren't my thread locks working properly?

对于一项作业,我应该创建一个简单的多线程程序,该程序具有三个等待随机时间(0.1 到 2 秒之间)的线程,然后打印 "end." I我正在尝试使用锁来防止切换弄乱输出,但我的输出看起来仍然是随机的(这意味着锁没有按预期工作)。 我的代码是:

import time
from threading import *
import random

lock = Lock()

def one():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("1. end")
    lock.release()

def two():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("2. end")
    lock.release()

def three():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("3. end")
    lock.release()


for i in range(0,100):
    t1 = Thread(target = one)
    t2 = Thread(target = two)
    t3 = Thread(target = three)
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()

但我的输出是:

 2. end
 3. end
 1. end
 3. end
 2. end
 2. end
 1. end
 3. end
 1. end
 etc...

我做错了什么?

随机休眠后获取锁:

import time
from threading import *
import random

lock = Lock()

def one():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("1. end")
    lock.release()

def two():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("2. end")
    lock.release()

def three():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("3. end")
    lock.release()


for i in range(0,100):
    t1 = Thread(target = one)
    t2 = Thread(target = two)
    t3 = Thread(target = three)
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()