zoukankan      html  css  js  c++  java
  • 线程同步应用

     1 import time
     2 from threading import Thread,Lock
     3 #创建3把互斥锁
     4 lock1 = Lock()
     5 lock2 = Lock()
     6 lock3 = Lock()
     7 #对lock2和lock3上锁
     8 lock2.acquire()
     9 lock3.acquire()
    10 
    11 class Task1(Thread):
    12     def run(self):
    13         while True:
    14             if lock1.acquire():
    15                 print('...task1...')
    16                 time.sleep(1)
    17                 #释放lock2的锁
    18                 lock2.release()
    19 class Task2(Thread):
    20     def run(self):
    21         while True:
    22             if lock2.acquire():
    23                 print('...task2...')
    24                 time.sleep(1)
    25                 #释放lock3的锁
    26                 lock3.release()
    27 class Task3(Thread):
    28     def run(self):
    29         while True:
    30             if lock3.acquire():
    31                 print('...task3...')
    32                 time.sleep(1)
    33                 #释放lock1的锁
    34                 lock1.release()
    35 if __name__ == '__main__':
    36     t1 = Task1()
    37     t2 = Task2()
    38     t3 = Task3()
    39     t1.start()
    40     t2.start()
    41     t3.start()
     1 ...task1...
     2 ...task2...
     3 ...task3...
     4 ...task1...
     5 ...task2...
     6 ...task3...
     7 ...task1...
     8 ...task2...
     9 ...task3...
    10 ......
    正是江南好风景
  • 相关阅读:
    测试理论
    字符串
    类的无参方法
    类和对象
    数组
    循环结构
    选择结构
    java——面对对象
    android通知的基本用法
    Git的基本使用
  • 原文地址:https://www.cnblogs.com/monsterhy123/p/12682935.html
Copyright © 2011-2022 走看看