62,614
社区成员
发帖
与我相关
我的任务
分享
public class ThreadTest {
public static void main(String[] args) {
new Thread(new ThreadDemo()).start();
}
}
class ThreadDemo implements Runnable {
private int i = 0;
public synchronized void run() {
try {
ThreadTest.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public class test1 {
private static final test1 t = new test1();
public static void main(String[] args) {
new Thread(new ThreadDemo(t)).start();
}
}
class ThreadDemo implements Runnable {
private int i = 0;
private test1 t = null;
public ThreadDemo(test1 t) {
this.t = t;
}
public void run() {
synchronized (t) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
------解决方案--------------------------------------------------------
如果不正确地管理wait/notify调用,应用程序可能会抛出IllegalMonitorStateException,例如,若不拥有对象的锁标记,而试图用wait/notify协调共享对象资源,应用程序将抛出IllegalMonitorStateException。
IllegalMonitorStateException意味着一个或多个资源可能不再处于一致状态,表示程序出现了严重问题。由于IllegalMonitorStateException是RuntimeException类型,因此它可能中断产生异常的线程。
public class ThreadTest {
public static void main(String[] args) {
new Thread(new ThreadDemo()).start();
}
}
class ThreadDemo implements Runnable {
private int i = 0;
public synchronized void run() {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
只有让当前执行的线程放弃对象锁,让其它正在等待的线程先执行。