按序打印(多线程同步机制)

 题目给出的初始代码:

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();
    }
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荔枝味啊~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值