在线程等待的间隙,其他的线程会进行唤醒的操作,这时候我们要用的notify()方法来进行处理。当notify()结束线程的唤醒工作,才会进行下一步的wait方法,也就是说notify()也可以结合wait对线程一起作用。下面我们就notify()的概念、语法、参数、返回值、使用注意,以及结合wait使用的实例带来介绍。
1.概念
随机唤醒一个在一样的对象监视器上等待的线程。通知一个在对象上等待的线程,也就是对象wait set中的线程,使其从wait()方法返回,而返回的前提是该线程获取到了对象的锁。
2.语法
publicfinalvoidnotify()
3.参数
无
4.返回值
没有返回值
5.使用注意
notify()也必须在同步方法或同步代码块中调用,用来唤醒等待该对象的其他线程。如果有多个线程在等待,随机挑选一个线程唤醒(唤醒哪个线程由JDK版本决定)。notify方法调用后,当前线程不会立刻释放对象锁,要等到当前线程执行完毕后再释放锁。
6.实例
注:wait()和notify()应当用在synchronized内
packagecom.test;
importjava.util.ArrayList;
publicclassThreadWaitTeste{
publicstaticvoidmain(String[]args){
ArrayList<String>ar=newArrayList<String>();
Productp=newProduct(ar);
Consumerc=newConsumer(ar);
Threadt1=newThread(p);
Threadt2=newThread(c);
t1.start();
t2.start();
}
}
classProductimplementsRunnable{
ArrayList<String>array;
publicProduct(ArrayList<String>array){
this.array=array;
}
publicvoidrun(){
while(true){
synchronized(array){
if(this.array.size()<5){
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
System.out.println("Productsize:"+array.size());
}else{
System.out.println("Productwaitsize:"+array.size()+"数量少于5,等待......");
try{
array.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
}
}
classConsumerimplementsRunnable{
ArrayList<String>array;
publicConsumer(ArrayList<String>array){
this.array=array;
}
publicvoidrun(){
while(true){
synchronized(array){
if(this.array.size()>=5){
this.array.remove(1);
System.out.println("Consumersize:"+array.size());
}else{
try{
array.notifyAll();
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
}
}
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    



















































 
        

暂无评论内容