python线程范例

简介

python线程学习与使用

示例

from threading import Thread
from threading import Barrier
from time import sleep

def function01(barrier):
    print('START function01 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('A')
    print('FINISH function01 !')

def function02(barrier):
    print('START function02 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('B')
    print('FINISH function02 !')

def function03(barrier):
    print('START function03 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('C')
    print('FINISH function03 !')

barrier = Barrier(3)
threads = []

t = Thread(target=function01, args=(barrier,))
t.start()
threads.append(t)

t = Thread(target=function02, args=(barrier,))
t.start()
threads.append(t)

t = Thread(target=function03, args=(barrier,))
t.start()
threads.append(t)

for t in threads:
   t.join()

运行结果

START function01 !
START function02 !
START function03 !
B
A
C
C
B
A
C
B
A
C
B
A
C
FINISH function03 !
B
FINISH function02 !
A
FINISH function01 !

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注