1115. 交替打印FooBar
Ideas交替锁的设计,两把锁,foo执行的时候把foo lock acquire,print完了只有把bar lock release,这样foo就得等着,然后bar执行的时候把bar lock acquire,print完了之后把foo lock release,这样就能交替打印foo和bar了。
Code Pythonfrom threading import Lock class FooBar: def __init__(self, n): self.n = n self.print_foo = Lock() self.print_bar = Lock() self.print_bar.acquire() def foo(self, printFoo: 'Callable[[], None]') -> None: for i in range(self.n): self.print_foo.acquire() # printFoo() outputs "foo". Do not change or remove this line. printFoo() self.print_bar.release() def bar(self, printBar: 'Callable[[], None]') -> None: for i in range(self.n): self.print_bar.acquire() # printBar() outputs "bar". Do not change or remove this line. printBar() self.print_foo.release()