2013-02-23 79 views
0

我想尝试使用Object本地方法wait()和notify()而不是Condition变量,但是这会引发IllegalMonitorStateException ...请解释如何使用它?你能解释为什么这段代码会引发异常吗?

package monitor; 


public class MyMonitor { 

private long threadID=0; 

Object okToWrite = new Object(); 
Object okToRead = new Object(); 

synchronized public void insertID() throws InterruptedException { 
    if (this.threadID != 0) { 
      okToWrite.wait(); 
    } 

    this.threadID = Thread.currentThread().getId(); 
    okToRead.notify(); 

} 

synchronized public long getID() throws InterruptedException { 
    long res; 

    if (this.threadID == 0) { 
     okToRead.wait(); 
    } 

    System.out.println(this.threadID); 
    res = this.threadID; 
    this.threadID = 0; 
    okToWrite.notify(); 

    return res; 

} 


} 

是否需要进一步锁定Object?

UPDATE: 广告尼尔建议,有必要之前调用wait对象上同步或通知......我们开始吧:

package monitor; 


public class MyMonitor { 

private long threadID=0; 

Object okToWrite = new Object(); 
Object okToRead = new Object(); 

public void insertID() throws InterruptedException { 
    if (this.threadID != 0) { 
     synchronized(okToWrite) { 
      okToWrite.wait(); 
     } 
    } 

    this.threadID = Thread.currentThread().getId(); 
    synchronized(okToRead) { 
     okToRead.notify(); 
    } 

} 

public long getID() throws InterruptedException { 
    long res; 

    if (this.threadID == 0) { 
     synchronized(okToRead) { 
      okToRead.wait(); 
     } 
    } 

    System.out.println(this.threadID); 
    res = this.threadID; 
    this.threadID = 0; 
    synchronized(okToWrite) { 
     okToWrite.notify(); 
    } 

    return res; 

} 


} 

回答

1

你也许可以让你的代码通过在同步工作对象,你想等待或通知,但我会同步显示对象上的所有东西:

package monitor; 

public class MyMonitor { 
    private long threadID = 0; 

    synchronized public void insertID() throws InterruptedException { 
     while (this.threadID != 0) { 
      wait(); 
     } 

     this.threadID = Thread.currentThread().getId(); 
     notify(); 
    } 

    synchronized public long getID() throws InterruptedException { 
     while (this.threadID == 0) { 
      wait(); 
     } 

     long res = this.threadID; 
     this.threadID = 0; 
     notify(); 

     return res; 
    } 
} 
+0

非常感谢!我明白了,不是有效的!我要发布正确的代码...谢谢你的朋友 – user1576208 2013-02-23 19:44:41

相关问题