浅谈java多线程wait,notify
前言
1.因为涉及到对象锁,Wait、Notify一定要在synchronized里面进行使用。
2.Wait必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行
3.notify/notifyall:唤醒线程
共享变量
publicclassShareEntity{
privateStringname;
//线程通讯标识
privateBooleanflag=false;
publicShareEntity(){
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicBooleangetFlag(){
returnflag;
}
publicvoidsetFlag(Booleanflag){
this.flag=flag;
}
}
线程1(生产者)
publicclassCommunicationThread1extendsThread{
privateShareEntityshareEntity;
publicCommunicationThread1(ShareEntityshareEntity){
this.shareEntity=shareEntity;
}
@Override
publicvoidrun(){
intnum=0;
while(true){
synchronized(shareEntity){
if(shareEntity.getFlag()){
try{
shareEntity.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
if(num%2==0)
shareEntity.setName("thread1-set-name-0");
else
shareEntity.setName("thread1-set-name-1");
num++;
shareEntity.setFlag(true);
shareEntity.notify();
}
}
}
}
线程2(消费者)
publicclassCommunicationThread2extendsThread{
privateShareEntityshareEntity;
publicCommunicationThread2(ShareEntityshareEntity){
this.shareEntity=shareEntity;
}
@Override
publicvoidrun(){
while(true){
synchronized(shareEntity){
if(!shareEntity.getFlag()){
try{
shareEntity.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
System.out.println(shareEntity.getName());
shareEntity.setFlag(false);
shareEntity.notify();
}
}
}
}
请求
@RequestMapping("test-communication")
publicvoidtestCommunication(){
ShareEntityshareEntity=newShareEntity();
CommunicationThread1thread1=newCommunicationThread1(shareEntity);
CommunicationThread2thread2=newCommunicationThread2(shareEntity);
thread1.start();
thread2.start();
}
结果
thread1-set-name-0 thread1-set-name-1 thread1-set-name-0 thread1-set-name-1 thread1-set-name-0 thread1-set-name-1 thread1-set-name-0
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗搜寻
2 如何训练狗狗装死
3 狗狗训练书
6 怎么训练狗狗拜年
8 狗狗训练游戏
10 狗狗嗅觉训练
11 怎么训练狗狗在笼子里不叫
12 怎么训练狗狗站立走路
13 怎么训练狗狗在马桶上
14 狗狗尿尿怎么训练
15 训练狗狗用品
16 泰迪狗狗的训练方法大小便
17 训练狗狗可以打吗
18 王曼丽的狗狗训练