【问题标题】:Mutual Exclusion using wait, synchronized, interrupt and notify使用等待、同步、中断和通知的互斥
【发布时间】:2017-11-04 03:02:38
【问题描述】:

有两个线程。一个是操纵 x,另一个是显示 x。如何使用同步、中断、等待和通知来实现互斥。图片显示了这一点。

Execution image

我想出了这个解决方案,但我不确定它是否正确。

synchronized(x){
    x = x + 1;
    notify();
    try{
        wait();
    }
    catch(InterruptedException e){
    }
}

阅读

synchronized(x){

    try{
         wait();
    }
    catch(InterruptedException e){
    }
    System.out.print(x);
}

【问题讨论】:

    标签: multithreading synchronization wait notify mutual-exclusion


    【解决方案1】:

    您已经使用synchronized(x) {} 闭包来确保不会发生这种情况。你在做什么是正确的。如果您的语句在单独的方法中,您还可以使您的方法同步,以便它在退出此方法之前不会受到影响。

    public synchronized void doSmth() {
        //do smth;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多