from threading import Thread, Lock import random

class Employee(Thread): def init(self, id, entrance, tickets): Thread.init(self) self.id = id self.entrance = entrance self.tickets = tickets

def run(self):
    global back_count, front_count
    ticket = [random.randint(1, 33) for i in range(6)]
    ticket.append(random.randint(1, 16))
    self.tickets[self.id] = ticket
    if self.entrance == 'back':
        print('{} 编号为: {} 的员工 从后门 入场! 拿到的双色球彩票号码是:{}'.format(self.id, self.id+1, ticket))
        lock.acquire()
        back_count += 1
        lock.release()
    else:
        print('{} 编号为: {} 的员工 从前门 入场! 拿到的双色球彩票号码是:{}'.format(self.id, self.id+1, ticket))
        lock.acquire()
        front_count += 1
        lock.release()

if name == 'main': lock = Lock() employees = [] tickets = {} back_count = 0 front_count = 0

for i in range(100):
    tickets[i] = []
    if i < 50:
        employees.append(Employee(i, 'back', tickets))
    else:
        employees.append(Employee(i, 'front', tickets))

for e in employees:
    e.start()

for e in employees:
    e.join()

print('从后门入场的员工总共: {} 位员工'.format(back_count))
print('从前门入场的员工总共: {} 位员工'.format(front_count))
Python 多线程模拟年会入场:统计员工人数和彩票号码

原文地址: https://www.cveoy.top/t/topic/oflR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录