python中的多线程----以2个线程卖票为例
#!/usr/bin/python# -*- coding: UTF-8 -*-#目标:线程1和线程2轮流切换卖100张票import timeimport threadingif __name__ == '__main__':con= threading.Condition()def job():global numcon.acquir
·
#!/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()
更多推荐
已为社区贡献7条内容
所有评论(0)