#!/usr/bin/python
# -*- coding: UTF-8 -*-
#目标:线程1和线程2轮流切换卖100张票
import time

import threading

if __name__ == '__main__':
   con= threading.Condition()
   def job():
      global num
      con.acquire()
      con.notify()
      if num>=1:
         try:
            print "线程%s正在售卖%d" % (threading.current_thread().name, num)
            num -= 1
         finally:
            con.wait()                        #两个线程都会持有锁,且不会释放了
   def task():
      while True:
         job()

   t3=threading.Thread(target=task,name="线程1")
   t4=threading.Thread(target=task,name="线程2")
   t3.start()
   t4.start()
 
 
 
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐