这个题解使用了四个线程来并发处理从1到n的数字,每个线程根据数字的特性(能否被3、5整除)来执行特定的打印任务。利用锁(Lock)和条件变量(Condition)来同步不同的线程,确保在任意时刻只有一个线程能够执行并修改共享资源current的值。每个方法(fizz, buzz, fizzbuzz, number)对应一个线程,它们在内部循环中检查当前数字(self.current)是否符合打印条件,如果符合则打印并通知其他线程,否则等待其他线程的通知。
时间复杂度: O(n)
空间复杂度: O(1)
from threading import Thread, Lock, Condition
class FizzBuzz:
def __init__(self, n: int):
self.n = n
self.lock = Lock()
self.cv = Condition(self.lock)
self.current = 1
def fizz(self, printFizz: 'Callable[[], None]') -> None:
with self.lock:
while self.current <= self.n:
if self.current % 3 == 0 and self.current % 5 != 0:
printFizz()
self.current += 1
self.cv.notify_all()
else:
self.cv.wait()
def buzz(self, printBuzz: 'Callable[[], None]') -> None:
with self.lock:
while self.current <= self.n:
if self.current % 5 == 0 and self.current % 3 != 0:
printBuzz()
self.current += 1
self.cv.notify_all()
else:
self.cv.wait()
def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:
with self.lock:
while self.current <= self.n:
if self.current % 3 == 0 and self.current % 5 == 0:
printFizzBuzz()
self.current += 1
self.cv.notify_all()
else:
self.cv.wait()
def number(self, printNumber: 'Callable[[int], None]') -> None:
with self.lock:
while self.current <= self.n:
if self.current % 3 != 0 and self.current % 5 != 0:
printNumber(self.current)
self.current += 1
self.cv.notify_all()
else:
self.cv.wait()
# 示例函数,用于打印字符串
def print_fizz():
print('fizz')
def print_buzz():
print('buzz')
def print_fizzbuzz():
print('fizzbuzz')
def print_number(x):
print(x)
# 初始化FizzBuzz实例,并启动线程
n = 15
fizz_buzz = FizzBuzz(n)
threads = [
Thread(target=fizz_buzz.fizz, args=(print_fizz,)),
Thread(target=fizz_buzz.buzz, args=(print_buzz,)),
Thread(target=fizz_buzz.fizzbuzz, args=(print_fizzbuzz,)),
Thread(target=fizz_buzz.number, args=(print_number,))
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()