【发布时间】: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