练习题-多线程

'''猴子5
桃100,
一次一只猴子吃桃-2-4'''
import threading
import time
import random
import queue
exitFlag = 0
all = 0
class MyThread(threading.Thread):

    def __init__(self,name ):
        threading.Thread.__init__(self)
        self.name = name

    def run(self):
        self.eat()

    def eat(self):
        global count,all
        while count>=2:
            lock.acquire()
            num = random.randint(2,4)
            if count-num>=0:
                count-=num
                all += num
                print('--{}---{}--{}'.format(self.name, num, time.ctime(time.time())))
                # time.sleep(1)
            lock.release()



count = 100

lock = threading.Lock()
a = MyThread('monkey-1' )
b = MyThread('monkey-2' )
c = MyThread('monkey-3' )
d = MyThread('monkey-4' )
e = MyThread('monkey-5' )

a.start()
b.start()
c.start()
d.start()
e.start()



a.join()
b.join()
c.join()
d.join()
e.join()

print('end - {} -- {}'.format(count,all))

你可能感兴趣的:(练习题-多线程)