java多线程中wait和notify一直是我学习中遗漏的一个地方,今天打算把这个坑填上
先贴代码:
package com.nice.test;
import org.junit.Test;
public class Demo implements Runnable{
public boolean flag = false;
private static Demo lock = new Demo() ;
@Override
public void run() {
synchronized (lock) {
if (!flag) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
System.out.println("线程继续执行");
}
}
public static void test() {
synchronized (lock) {
lock.notify();
}
}
public static void main(String[] args) {
Demo demo = new Demo();
Thread thread = new Thread(demo);
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (demo.flag == false) {
test();
}
}
}
wait和notiry必须使用同步方法,而且必须使用同一把锁,不然会抛出Exception in thread "main" java.lang.IllegalMonitorStateException异常,而且锁不能为null,否则会抛出空指针异常