【问题标题】:Java IllegalMonitorStateException [duplicate]Java IllegalMonitorStateException [重复]
【发布时间】:2015-07-09 18:06:43
【问题描述】:

我需要一些帮助来了解我的程序哪里出了问题,我有一个非常简单的程序来学习多线程,但是每次我运行以下代码时,它都会给我一个 IllegalStateMonitorException。我不知道是什么原因造成的,尽管我怀疑它可能是我的同步块,谢谢。

主要方法类:

public class Lab8 {
    public static void main(String [] args) { 
        Thread1 thread1 = new Thread1(); 
        thread1.start();
    }
}

线程 1:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Thread1 extends Thread {
public DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

public Thread1() { 
    super("Thread1");
}
public void run() { 
    Thread2 thread2 = new Thread2(); 
    System.out.println("==Start: " + dateFormat.format(new Date()) + "==\n"); 
    synchronized(thread2) { 
        try {
            this.wait();
        } catch (InterruptedException e) {
            System.err.println(e.toString()); 
        } 
        (new Thread(thread2)).start(); 
    }
    System.out.println("==End: " + dateFormat.format(new Date()) + "==\n"); 
}
}

线程 2:

public class Thread2 implements Runnable {
@Override
public void run() {
    synchronized(this) { 
        for(int i = 1; i <= 100; i++) { 
            System.out.print(i + " ");
            if(i % 10 == 0) { 
                System.out.print("\n");
            }
        }
        notify(); 
    }
} 

}

【问题讨论】:

  • 如果您遇到异常,将堆栈跟踪包含在您的问题中会很有帮助。
  • 不仅仅是在这里包含,而是自己阅读。如果您已阅读堆栈跟踪,那么您就不必“怀疑它可能在我的同步块中:”您将知道确切的代码行引发了异常。跨度>

标签: java multithreading


【解决方案1】:

您应该明白,synchronized 构造和wait/notify 机制与对象实例相关联。在您的代码中,您正在使用

synchronized(thread2) { 
   …
        this.wait();

所以你的synchronized 语句的对象和你调用wait 的对象是不同的。这会导致IllegalStateMonitorException。请注意,当另一个线程在自己的Thread2 实例上调用notify() 时,在Thread1 实例上等待将不起作用,因为notify 只会唤醒等待在同一实例上的线程。

除此之外,您永远不应该在线程实例上进行同步。原因是Thread 实现也会在它自己的实例上同步,所以这可能会干扰。此外,您不应该像使用 Thread1 类那样子类化 Thread,而应该像使用 Thread2 类那样使用组合。

【讨论】:

  • 是的,但扩展Thread 并没有真正错误,只是糟糕的设计。
  • @james large:嗯,我在结尾说明中说“不应该”,这并不是一个教条规则,但是,这是导致意外同步或等待线程的模式只需使用this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2011-10-30
  • 2014-08-03
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多