题目描述
我们提供了一个类:
public class Foo{
public void one(){ print("one");}
public void two(){ print("two");}
public void three(){ print("three");}
}
三个不同的线程将会共用一个Foo
实例。
- 线程A将会调用
one()
方法 - 线程B将会调用
two()
方法 - 线程C将会调用
three()
方法
请设计修改程序,以确保two()
方法在one()
方法之后被执行,three()
方法在two()
方法之后被执行。
示例1:
输入:[1, 2, 3]
输出:"onetwothree"
解析:
有三个线程会被异步启动。
输入[1,2,3]表示线程A将会调用one()方法,线程B将会调用two()方法,线程C将会调用three()方法。
正确的输出是“onetwothree”。
示例2:
输入:[1,3,2]
输出:"onetwothree"
解析:
输入[1,3,2]表示线程A将会调用one()方法,线程B将会调用three()方法,线程C将会调用two()方法。
正确的输出是:"onetwothree"
注意:
尽管输入中的数字似乎暗示了顺序,但是我们并不能保证线程在操作系统中的调度顺序。
你看到的输入格式主要是为了确保测试的全面性。
算法设计分析:
- 可以这样想,两种方法:睡眠大法和锁大法(显然睡眠大法不严谨,只提供思路)。
- 1、首先我们面对的是三个线程,要想按照顺序打印出onetwothree的话,首先是要调用one(),然后调用two(),最后调用three(),但是线程的执行不是事先已经分好先后,他们会争着抢到时间片来运行自己的程序。这样我们可以先让后面的sleep一下,前面的先执行,执行完成之后,后面的也醒了。
- 2、方法一是有严重的缺陷的,当程序复杂的时候,睡多长时间,这是个严重的问题。因此,加锁是终极方法。首先需要一把锁,锁的状态有四种0,1,2,3,分别对应程序结束和三个线程A,B,C。可以先令锁初始化状态为1,运行线程A使得A调用one()方法,A线程执行完成之后,设置锁的状态为2,线程B调用two()方法,…,最后线程C调用three()方法,设置锁为0,程序结束:
- python3描述方法一:
import time
class Foo:
def __init__(self):
pass
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
def second(self, printSecond: 'Callable[[], None]') -> None:
# printSecond() outputs "second". Do not change or remove this line.
time.sleep(0.01)
printSecond()
def third(self, printThird: 'Callable[[], None]') -> None:
# printThird() outputs "third". Do not change or remove this line.
time.sleep(0.02)
printThird()
- python3描述方法二:
class Foo:
def __init__(self):
self.mutex = 1
pass
def first(self, printFirst: 'Callable[[], None]') -> None:
while self.mutex != 1:
pass
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.mutex = 2
def second(self, printSecond: 'Callable[[], None]') -> None:
while self.mutex != 2:
pass
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
self.mutex = 3
def third(self, printThird: 'Callable[[], None]') -> None:
while self.mutex != 3:
pass
# printThird() outputs "third". Do not change or remove this line.
printThird()
self.mutex = 0