仅提供学习,侵权必删,如有错误,敬请告知
一、wait 和 notifyAll
package Suo8;
public class Huanxing {
private static final String XIAOMING_STRING = "小明";
private static volatile boolean zhuangtai = false;
public static void xiaoming() {
synchronized (XIAOMING_STRING) {
System.out.println("小明在睡觉,三秒等待小李唤醒!");
try {
XIAOMING_STRING.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("小明起床,动作结束");
}
}
public static void xiaoli() {
System.out.println("三秒钟时间到,小李准备唤醒小明");
synchronized (XIAOMING_STRING) {
XIAOMING_STRING.notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
xiaoming();
}
};
thread.start();
while (!zhuangtai) {
for (int i = 1; i <= 3; i++) {
Thread.sleep(1000);
System.out.println("已过去"+i+"秒");
}
zhuangtai = true;
}
Thread thread1 = new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
xiaoli();
}
};
thread1.start();
}
}