力扣交替打印FooBar

这道题要注意的是两个线程唤醒和等待的顺序,应为第一个线程会比第二个线程更早结束,所以如果第一个线程已经结束,而第二个线程还在等待被唤醒,那第二个线程会一直等待下去,因此第一个线程要先等待后唤醒,这样他会先唤醒第二个线程再结束

  • 语无伦次,直接看代码吧
from threading import Condition, Thread
import time


def printFoo():
    print('foo', end='')
    time.sleep(0.5)


def printBar():
    print('bar', end='')
    time.sleep(0.5)


class FooBar:
    def __init__(self, n):
        self.n = n
        self._lock = Condition()


    def foo(self, printFoo) -> None:
        self._lock.acquire()
        for i in range(self.n):
            printFoo()
            # 这里要先等待
            self._lock.wait()
            self._lock.notify_all()
        self._lock.release()


    def bar(self, printBar) -> None:
        self._lock.acquire()
        for i in range(self.n):
            printBar()
            # 这里要先唤醒其他线程,
            self._lock.notify_all()
            self._lock.wait()
        self._lock.release()

if __name__ == '__main__':
    n = 10
    foobar = FooBar(n)
    t1 = Thread(target=foobar.foo, args=(printFoo,))
    t2 = Thread(target=foobar.bar, args=(printBar,))
    # t2.start()
    t1.start()
    t2.start()

执行用时 :132 ms, 在所有 Python3 提交中击败了85.39%的用户
内存消耗 :16.1 MB, 在所有 Python3 提交中击败了100.00%的用户

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Junebao

如果你碰巧财力雄厚的话...

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值