package com.xiaonei2shou.test;
public class ThreadTest {
private String flag = "true";
class NotifyThread extends Thread {
public NotifyThread(String name) {
super(name);
}
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (flag) {
flag = "false";
flag.notifyAll();
}
}
};
class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}
public void run() {
synchronized (flag) {
while (flag != "false") {
long waitTime = System.currentTimeMillis();
System.out.println(getName() + " begin waiting!");
try {
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime = System.currentTimeMillis() - waitTime;
System.out.println(getName() + " wait time :" + waitTime);
try {
sleep(1000);
System.out.println(getName() + " sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " end waiting!");
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Thread Run!");
ThreadTest test = new ThreadTest();
NotifyThread notifyThread = test.new NotifyThread("notify01");
WaitThread waitThread01 = test.new WaitThread("waiter01");
WaitThread waitThread02 = test.new WaitThread("waiter02");
WaitThread waitThread03 = test.new WaitThread("waiter03");
waitThread02.start();
waitThread01.start();
waitThread03.start();
notifyThread.start();
}
}
Exception in thread "notify01" java.lang.IllegalMonitorStateException 报错了 啥原因
------解决方案--------------------
给你把代码调了下,变动的地方加了注释:
public class ThreadTest {
private String flag = "true";
private Object locker = new Object();
class NotifyThread extends Thread {
public NotifyThread(String name) {
super(name);
}
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 使用专门的Object对象作为测试wait和notify的锁
//因为当flag从"true"变成"false"时,flag指向的对象已经变了
synchronized (locker) {
flag = "false";
locker.notifyAll();
}
}
};
class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}
public void run() {
// wait和nonify都用一个Object对象实现
synchronized (locker) {
// 字符串不能用=或者!=比较
while (!flag .equals("false")) {
long waitTime = System.currentTimeMillis();
System.out.println(getName() + " begin waiting!");
try {