Java多线程通信wait()和notify()代码实例
1.wait()方法和sleep()方法:
wait()方法在等待中释放锁;sleep()在等待的时候不会释放锁,抱着锁睡眠。
2.notify():
随机唤醒一个线程,将等待队列中的一个等待线程从等待队列中移到同步队列中。
代码如下
publicclassDemo_Print{
publicstaticvoidmain(String[]args){
Printp=newPrint();
newThread(){
publicvoidrun(){
while(true){
p.print1();
}
};
}.start();
newThread(){
publicvoidrun(){
while(true){
p.print2();
}
};
}.start();
}
}
classPrint{
intflag=1;
publicsynchronizedvoidprint1(){
if(flag!=1){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("你");
System.out.print("好");
System.out.print("吗????????????");
System.out.println();
flag=2;
this.notify();
}
publicsynchronizedvoidprint2(){
if(flag!=2){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("我");
System.out.print("好");
System.out.println();
flag=1;
this.notify();
}
}
在该案例中,实现一问一答的线程同步通信。当方法中开启了wait()方法后,通过改变flag的值来唤醒线程进而实行另一个方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西