题目给出的初始代码:
class Foo {
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line. printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
这道题是一道很简单的多线程问题,一般来讲线程时并发的,但如果所有线程都并发那就会产生很多问题,比如两个人同时对同一张***取钱,可能第一个人取完钱余额还没减少的时候第二个人还能再取,所以就有了线程同步机制,多线程并发属于异步机制
同步机制需要用到synchronized关键字,我们每一个线程对象都有一个对象锁,当一个线程抢到了对象锁就可执行代码,执行完了就会释放对象锁,
但是有一点很重要,就是异步线程必须有共享对象,所以我们需要创建一共享对象lock
然后我们在执行2的时候必须保证1已经执行,所以我们给1设置一个状态码初始为false(firstCode=false),1完成后改为true,3同理
所以while(firstCode==false){
lock.wait();//1没完成2要等待
}
当然1完成后要唤醒其他xianch,lock.notifyAll();
完整代码如下:
class Foo {
private boolean firstCode=false;
private boolean secondCode=false;
private Object lock=new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized(lock){
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstCode=true;
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized(lock){
// printSecond.run() outputs "second". Do not change or remove this line.
while(firstCode==false){
lock.wait();
}
printSecond.run();
secondCode=true;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized(lock){
// printThird.run() outputs "third". Do not change or remove this line.
while(secondCode==false){
lock.wait();
}
printThird.run();
}
}
}