notify()和wait()实现:
this.notify():随机唤醒单个等待线程。
this.wait():当前线程等待,wait()若无人唤醒,则一直等待;而Thread.sleep是睡眠一定时间后再次启动。
public class DemoNotify {
public static void main(String[] args) {
final Print p=new Print();
new Thread(){
public void run(){
while (true){
try {
p.print1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
while (true){
try {
p.print2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Print{
private int flag=1;
public void print1() throws Exception{
synchronized(this){
if (flag!=1){
this.wait(); //当前线程等待,wait()若无人唤醒,则一直等待;而Thread.sleep是睡眠一定时间后再次启动
System.out.println("等待一");
}
System.out.print("1");
System.out.print("2");
System.out.print("3");
System.out.print("4");
System.out.println("5");
flag=2;
this.notify(); //随机唤醒单个等待线程
}
}
public void print2() throws Exception{
synchronized(this){
if (flag!=2){
this.wait();
System.out.println("等待二");
}
System.out.print("上");
System.out.print("山");
System.out.print("打");
System.out.print("老");
System.out.println("虎");
flag=1;
this.notify();
}
}
}
运行结果:
12345
上山打老虎
等待一
12345
等待二
上山打老虎
等待一
12345
等待二
上山打老虎
等待一