如果我程序调用wait()方法的时候就会报java.lang.IllegalMonitorStateException,这个异常,wait()不是让线程等待的吗?而与之想对应的有notify()唤醒等待的线程和唤醒全部的线程notifyAll()方法,我也同样掉用了。为什么还是报错。是不是我用的方式错误了?
class A{
synchronized void ThreadB(B b){
String name = Thread.currentThread().getName();
System.out.println(name+" entered A.ThreadA");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last(){
System.out.println("Inside A.last");
}
}
class B {
synchronized void ThreadA(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.ThreadB");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
Thread t = new Thread(this, "RacingThread");
t.start();
}
@Override
public void run() {
b.ThreadA(a);
try {
// wait();////这个方法不是等待线程吗?为什么我写这行代码就会报错
} catch (Exception e) {
e.printStackTrace();
}
// notify();//这个方法不是唤醒等待的线程吗?
Thread.currentThread().setName("线程名称:");
a.ThreadB(b);
System.out.println("Bcak in main thread");
}
public static void main(String args[]) {
new Deadlock();
}
}
|
|