我们提供了一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo
实例。
- 一个将会调用
first()
方法 - 一个将会调用
second()
方法 - 还有一个将会调用
third()
方法
请设计修改程序,以确保 second()
方法在 first()
方法之后被执行,third()
方法在 second()
方法之后被执行。
示例 1:
输入: [1,2,3] 输出: "firstsecondthird" 解释: 有三个线程会被异步启动。 输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。 正确的输出是 "firstsecondthird"。
示例 2:
输入: [1,3,2] 输出: "firstsecondthird" 解释: 输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。 正确的输出是 "firstsecondthird"。
示例代码1:
from threading import Lock
class Foo:
def __init__(self):
self.firstJob = Lock()
self.firstJob.acquire()
self.secondJob = Lock()
self.secondJob.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.firstJob.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
with self.firstJob:
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
self.secondJob.release()
def third(self, printThird: 'Callable[[], None]') -> None:
with self.secondJob:
# printThird() outputs "third". Do not change or remove this line.
printThird()
测试代码:
from threading import Lock
from threading import Thread
class Foo(object):
def __init__(self):
self.firstJob = Lock()
self.secondJob = Lock()
self.firstJob.acquire()
self.secondJob.acquire()
def first(self):
print('first')
self.firstJob.release()
def second(self):
with self.firstJob:
print('second')
self.secondJob.release()
def third(self):
with self.secondJob:
print('third')
if __name__ == '__main__':
lst = [1, 3, 2]
obj = Foo()
for i in lst:
if i == 1:
first = Thread(target=obj.first)
first.start()
elif i == 2:
second = Thread(target=obj.second)
second.start()
else:
third = Thread(target=obj.third)
third.start()
运行效果: