品易云推流 关闭
文章详情页
文章 > java基础 > java notify()的唤醒

java notify()的唤醒

java notify唤醒

头像

小妮浅浅

2021-01-08 14:12:042940浏览 · 0收藏 · 0评论

在线程等待的间隙,其他的线程会进行唤醒的操作,这时候我们要用的notify()方法来进行处理。当notify()结束线程的唤醒工作,才会进行下一步的wait方法,也就是说notify()也可以结合wait对线程一起作用。下面我们就notify()的概念、语法、参数、返回值、使用注意,以及结合wait使用的实例带来介绍。

1.概念

随机唤醒一个在一样的对象监视器上等待的线程。通知一个在对象上等待的线程,也就是对象wait set中的线程,使其从wait()方法返回,而返回的前提是该线程获取到了对象的锁。

2.语法

public final void notify()

3.参数

4.返回值

没有返回值

5.使用注意

notify()也必须在同步方法或同步代码块中调用,用来唤醒等待该对象的其他线程。如果有多个线程在等待,随机挑选一个线程唤醒(唤醒哪个线程由JDK版本决定)。notify方法调用后,当前线程不会立刻释放对象锁,要等到当前线程执行完毕后再释放锁。

6.实例

注:wait()和notify()应当用在synchronized内
package com.test;
import java.util.ArrayList;
public class ThreadWaitTeste {
public static void main(String[] args) {
ArrayList<String> ar = new ArrayList<String>();
Product p = new Product(ar);
Consumer c = new Consumer(ar);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Product implements Runnable{
ArrayList<String>  array;
public Product(ArrayList<String> array){
this.array= array;
}
public void run() {
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("Product size : "+array.size());
}else{
System.out.println("Product wait size : "+array.size()+"数量少于5,等待......");
try {
array.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class Consumer implements Runnable{
ArrayList<String>  array;
public Consumer(ArrayList<String> array){
this.array= array;
}
public void run() {
while(true){
synchronized(array){
if(this.array.size()>=5){
this.array.remove(1);
System.out.println("Consumer size : "+array.size());
}else{
try {
array.notifyAll();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

以上就是java中notify()的唤醒方法,同时结合了wait的使用,完成了线程的等待和唤醒过程。看完基本的notify()知识点后,就可以进行实战的操作了。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图