Java object wait notify notifyAll代码解析
测试代码:
publicstaticObjectloc=newObject();
publicstaticvoidmain(String[]args)throwsException{
Threadt1=newThread(newRunnable(){
@Override
publicvoidrun(){
try{
java.text.SimpleDateFormatsdf=newSimpleDateFormat("HH:mm:ssSSS");
System.out.println("["+sdf.format(newDate())+"]t1___等待锁...");
synchronized(loc){
System.out.println("["+sdf.format(newDate())+"]t1___获得锁...");
Thread.sleep(5000);
System.out.println("["+sdf.format(newDate())+"]t1___loc..开始执行wait...");
loc.wait();
System.out.println("["+sdf.format(newDate())+"]t1___loc..执行wait后续...");
Thread.sleep(1000);
}
System.out.println("["+sdf.format(newDate())+"]t1___loc..离开锁...");
}catch(Exceptione){
e.printStackTrace();
}
}
});
Threadt3=newThread(newRunnable(){
@Override
publicvoidrun(){
try{
java.text.SimpleDateFormatsdf=newSimpleDateFormat("HH:mm:ssSSS");
System.out.println("["+sdf.format(newDate())+"]t3___等待锁...");
synchronized(loc){
System.out.println("["+sdf.format(newDate())+"]t3___进入锁...");
Thread.sleep(5000);
System.out.println("["+sdf.format(newDate())+"]t3___loc..开始wait...");
loc.wait();
System.out.println("["+sdf.format(newDate())+"]t3___loc..执行wait后续...");
Thread.sleep(1000);
}
System.out.println("["+sdf.format(newDate())+"]t3___离开锁...");
}catch(Exceptione){
e.printStackTrace();
}
}
});
Threadt2=newThread(newRunnable(){
@Override
publicvoidrun(){
try{
java.text.SimpleDateFormatsdf=newSimpleDateFormat("HH:mm:ssSSS");
System.out.println("["+sdf.format(newDate())+"]t2___等待锁...");
synchronized(loc){
System.out.println("["+sdf.format(newDate())+"]t2___获得锁...");
Thread.sleep(5000);
System.out.println("["+sdf.format(newDate())+"]t2___loc..开始执行notify...");
loc.notify();
System.out.println("["+sdf.format(newDate())+"]t2___loc..执行notify后续...");
Thread.sleep(1000);
}
System.out.println("["+sdf.format(newDate())+"]t2___loc离开锁....");
}catch(Exceptione){
e.printStackTrace();
}
}
});
t1.start();
t3.start();
Thread.sleep(500);
t2.start();
System.out.println("t1___beforejoin....");
t1.join();
System.out.println("t2___beforejoin....");
t2.join();
System.out.println("t3____beforejoin....");
t3.join();
System.out.println("mainexit....");
}
执行结果:
[16:55:59384]t1___等待锁...
[16:55:59384]t1___获得锁...
[16:55:59384]t3___等待锁...
t1___beforejoin....
[16:55:59836]t2___等待锁...
[16:56:04392]t1___loc..开始执行wait...[16:56:04392]t2___获得锁...
[16:56:09392]t2___loc..开始执行notify...
[16:56:09392]t2___loc..执行notify后续...
[16:56:10392]t2___loc离开锁....
[16:56:10392]t3___进入锁...
[16:56:15392]t3___loc..开始wait...
[16:56:15392]t1___loc..执行wait后续...
[16:56:16392]t1___loc..离开锁...
t2___beforejoin....
t3____beforejoin....
总结:
1.执行wait后‘'暂时‘释放当前对象锁给其他线程,当前线程处于等待状态
2.syn块中的wait收到notify通知后唤醒cpu继续判断锁状态
3.执行notify且当前的对象锁释放后wait等待的线程激活
4.notifyAll是一次唤醒所有的wait
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。