假设有这么一个类:
class ZeroEvenOdd {
public ZeroEvenOdd(int n) { ... } // 构造函数
public void zero(printNumber) { ... } // 仅打印出 0
public void even(printNumber) { ... } // 仅打印出 偶数
public void odd(printNumber) { ... } // 仅打印出 奇数
}
相同的一个 ZeroEvenOdd
类实例将会传递给三个不同的线程:
- 线程 A 将调用
zero()
,它只输出 0 。 - 线程 B 将调用
even()
,它只输出偶数。 - 线程 C 将调用
odd()
,它只输出奇数。
每个线程都有一个 printNumber
方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506
... ,其中序列的长度必须为 2n。
示例 1:
输入:n = 2 输出:"0102" 说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 "0102"。
示例 2:
输入:n = 5 输出:"0102030405"
示例代码:
from threading import Lock
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.zeroLock = Lock()
self.evenLock = Lock()
self.oddLock = Lock()
self.evenLock.acquire()
self.oddLock.acquire()
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1, 1):
self.zeroLock.acquire()
printNumber(0)
if i % 2 == 0:
self.evenLock.release()
else:
self.oddLock.release()
def even(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1, 1):
if i % 2 == 0:
self.evenLock.acquire()
printNumber(i)
self.zeroLock.release()
def odd(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1, 1):
if i % 2 == 1:
self.oddLock.acquire()
printNumber(i)
self.zeroLock.release()
三把锁(奇数锁、偶数锁、0锁)
输出之前先抢锁, even/odd 输出后释放zero锁,zero 输出做取余判断释放 even/odd 锁。
测试代码:
from threading import Lock, Thread
class ZeroEvenOdd(object):
def __init__(self, n):
self.n = n
self.stack = []
# 创建3把锁
self.zeroLock = Lock()
self.evenLock = Lock()
self.oddLock = Lock()
self.evenLock.acquire() # 偶数print加锁
self.oddLock.acquire() # 奇数print加锁
def zero(self):
for i in range(1, self.n + 1, 1):
self.zeroLock.acquire()
self.stack.append(0)
if i % 2 == 0:
self.evenLock.release()
else:
self.oddLock.release()
def even(self):
for i in range(1, self.n + 1, 1):
if i % 2 == 0:
self.evenLock.acquire()
self.stack.append(i)
self.zeroLock.release()
def odd(self):
for i in range(1, self.n + 1, 1):
if i % 2 == 1:
self.oddLock.acquire()
self.stack.append(i)
self.zeroLock.release()
def __del__(self):
print(''.join([str(i) for i in self.stack]))
if __name__ == '__main__':
n = 5
obj = ZeroEvenOdd(n)
zero = Thread(target=obj.zero)
zero.start()
even = Thread(target=obj.even)
even.start()
odd = Thread(target=obj.odd)
odd.start()
运行效果: