欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python多线程:小牛吃草案例

程序员文章站 2024-03-21 23:10:34
...
# By Chang

"""
Cow
    weight 0-5//体重标志牛 吃草次数
    tag= //标志牛是否长大
    eat() 吃草
Rain
    ifRain() //判断是否下雨
Grass
    height 0-3 //高度标志草是否成熟
    isRipe //艹是否成熟
    grow()// 草成长。

"""
import random
import threading
import time


class Cow:
    def __init__(self):
        self.weight = 0
        self.tag = False

    def eat(self):
        if self.weight < 5:
            self.weight += 1
        if self.weight == 5:
            self.tag = True


class Rain:
    @staticmethod
    def if_rain():
        temp = random.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
        return temp < 2
        # 下雨的概率只有20%


class Grass:
    def __init__(self):
        self.height = 0
        self.isRipe = False

    def grow(self):

        if self.height < 3:
            self.height += 1
        if self.height == 3:
            self.isRipe = True


class CowThread(threading.Thread):
    def __init__(self, threadId, cow):
        threading.Thread.__init__(self)
        self.threadId = threadId
        self.cow = cow

    def run(self):
        print(str(self.threadId) + "号线程开始")
        while not self.cow.tag:
            lock.acquire()
            if grass.isRipe:
                self.cow.eat()
                grass.height = 0
                grass.isRipe = False
                temp = str(self.threadId) + "号牛把草吃完了"
                write_line(temp)
            lock.release()
        print(str(self.threadId) + "号牛长大了")
        write_line(str(self.threadId) + "号牛长大了")


lock = threading.Lock()
flock = threading.Lock()
grass = Grass()
cows = []
threads = []


for i in range(10):
    cows.append(Cow())

i = 1
for cow in cows:
    threads.append(CowThread(i, cow))
    i += 1

# 如果文件已存在则清空,不存在则新建
f = open("log.txt", "w", encoding="utf-8")
f.close()

for t in threads:
    # t.setDaemon(True)
    t.start()


def write_line(line):
    f = open("log.txt", "a", encoding="utf-8")
    flock.acquire()
    f.write(time.ctime(time.time()) + ' ' + line + '\n')
    flock.release()
    f.close()


def day_start(grass):
    if Rain.if_rain():
        lock.acquire()
        if not grass.isRipe:
            grass.grow()
            temp = "下雨了," + "草长到了" + str(grass.height) + "英寸"
            write_line(temp)
        else:
            temp = "下雨了," + "草已经长大了"
            write_line(temp)
        lock.release()
    else:
        temp = "天没下雨"
        write_line(temp)


while 1:
    day_start(grass)
    label = True
    # TODO 调整判断策略
    for cow in cows:
        if not cow.tag:
            label = cow.tag
            break
    if label:
        break

for t in threads:
    t.join()
print("mainThread exit")

python多线程:小牛吃草案例

相关标签: python