Java 在整数上同步时,notify()上出现IllegalMonitorStateException
我不熟悉在Java中使用wait()和notify(),我得到了一个非法的MonitorStateException 主代码Java 在整数上同步时,notify()上出现IllegalMonitorStateException,java,wait,notify,illegalmonitorstateexcep,Java,Wait,Notify,Illegalmonitorstateexcep,我不熟悉在Java中使用wait()和notify(),我得到了一个非法的MonitorStateException 主代码 public class ThreadTest { private static Integer state = 0; public static void main(String[] args) { synchronized(state) { System.out.println("Starting threa
public class ThreadTest {
private static Integer state = 0;
public static void main(String[] args) {
synchronized(state) {
System.out.println("Starting thread");
Thread t = new Thread(new AnotherTest());
t.start();
synchronized(state) {
state = 0;
while(state == 0) {
try {
state.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("State is: " + state);
}
}
}
public static class AnotherTest implements Runnable {
@Override
public void run() {
synchronized(state) {
state = 1;
state.notify();
}
}
}
}
我得到一个非法的MonitorStateException调用了什么state.notify()。有什么想法吗
编辑:根据下面的答案,这里是有效的代码。顺便说一句,我第一次尝试使用一个枚举,它与使用整数有相同的问题
public class ThreadTest {
private static int state = 0;
private static Object monitor = new Object();
public static void main(String[] args) {
synchronized(monitor) {
System.out.println("Starting thread");
Thread t = new Thread(new AnotherTest());
t.start();
state = 0;
while(state == 0) {
try {
for(int i = 0; i < 5; i++) {
System.out.println("Waiting " + (5 - i) + " Seconds");
Thread.sleep(1000);
}
monitor.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("State is: " + state);
}
}
public static class AnotherTest implements Runnable {
@Override
public void run() {
synchronized(monitor) {
state = 1;
monitor.notify();
}
}
}
}
公共类线程测试{
私有静态int状态=0;
私有静态对象监视器=新对象();
公共静态void main(字符串[]args){
同步(监视器){
System.out.println(“起始线程”);
线程t=新线程(新的另一个测试());
t、 start();
状态=0;
while(state==0){
试一试{
对于(int i=0;i<5;i++){
System.out.println(“等待”+(5-i)+“秒”);
睡眠(1000);
}
监视器。等待(1000);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
System.out.println(“状态为:“+状态”);
}
}
公共静态类另一个测试实现Runnable{
@凌驾
公开募捐{
同步(监视器){
状态=1;
monitor.notify();
}
}
}
}
这个
private static Integer state = 0;
相当于
private static Integer state = Integer.valueOf(0);
state = Integer.valueOf(1);
调用valueOf(0)
返回对Integer
对象的引用,称之为a
那你会的
synchronized(state) {
state = 1;
线程获取由state
引用的对象上的锁,当前该对象是A
那你会的
synchronized(state) {
state = 1;
这相当于
private static Integer state = Integer.valueOf(0);
state = Integer.valueOf(1);
这为您提供了一个对整数
对象的不同引用,将其称为B,并将其分配给状态
。你什么时候打电话来
state.notify();
您正在对一个对象B调用
notify()
,而您的线程并不拥有该对象的监视器。您不能对线程不拥有监视器的对象调用notify
或wait
。这说明了如果您的代码依赖于更改等待对象的值,那么在不可变对象上使用wait/notify
是毫无意义的……谢谢!我知道我错过了一些非常直接的东西。