我的代码出问题了。
我的代码在 Hoge 类的 setStr
中抛出 IllegalMonitorStateException
。
我在setStr
中将Hoge.class
改成了this
。我的代码正确完成了!
但是为什么正常结束呢?
public class Sample {
static Hoge gh = new Hoge();
static Hoge gh2 = new Hoge();
public static void main(String[] args) {
new Thread() {
private Hoge h2 = gh;
public void run() {
System.out.println("start initialize");
h2.setStr("BazzBazz");
System.out.println("end initialize");
System.out.println("start thread 1");
System.out.println(h2.getStr("thread-1"));
System.out.println("end thread 1");
}
}.start();
new Thread() {
private Hoge h2 = gh2;
public void run() {
System.out.println("start thread 2");
System.out.println(h2.getStr("thread-2"));
System.out.println("end thread 2");
}
}.start();
}
}
class Hoge {
private String fuga = "fugafuga";
public void setStr(String str) {
synchronized(Hoge.class) { //<-HERE ! change "Hoge.class" into "this".
fuga = str;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
String getStr(String suffix) {
synchronized(Hoge.class) {
return suffix+ fuga;
}
}
}
最佳答案
您的setStr
方法应该是这样的:
public void setStr(String str) {
synchronized(Hoge.class) { //<-HERE ! change "Hoge.class" into "this".
fuga = str;
try {
Hoge.class.wait();//call wait on Hoge.class
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
您应该使用 Hoge.clas.wait()
而不是 wait()
。为什么?
因为 ,如 oracle documentation about wait() 中所述:
This method should only be called by a thread that is the owner of this object's monitor.
即 线程在拥有该对象的锁之前不能对该对象调用等待
。否则它会抛出 IllegalMonitorStateException
.在这里,您正在获取对 Hoge(即 Hoge.class)的 Class
对象的锁定,称为 class level lock
,但正在调用 wait
Hoge
(this
) 的当前对象。所以它导致 IllegalMonitorStateException
。这就是为什么当您获取当前对象 (this
) 的锁时您的代码工作正常的原因,因为在这种情况下 wait()
是在当前对象 (this) 上调用的
) 本身。
关于java - java中的多线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584854/