浅谈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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。