您的位置 首页 java

Java多线程中的等待/通知机制

Java 语言中,任意的对象都有等待/通知的方法,因为这些方法被定义在所有对象的超类java.lang.Object上,对应的方法就是wait()/notify(),具体解释如下:

wait():调用该方法的线程会进入WAITING状态,只有等待另外 线程 的通知或者被中断才会返回,调用wait()方法后会释放对象的锁,并且还提供了超时返回的方法wait( long )和wait(long,int)

notify():通知一个在对象上等待的锁,使其从wait()方法返回,返回的前提是该线程获取到了对象的锁

notifyAll():通知所有等待在该对象上的线程

所谓的等待/通知机制,就是一个线程A如果调用了对象O的wait()方法进入等待状态,而另外一个线程B调用了对象O的notify()或者notifyAll()方法,线程A收到通知后从对象O的wait()方法返回,进而执行后续操作。这两个线程通过对象O来完成交互,通过wait()和notify()方法来完成等待方和通知方的工作交互,这也是生产者-消费者模式的基础。

下面通过一道经典的面试题来说明wait()/notify()的用法:

public class ListAddTest00 {
private static volatile List list = new ArrayList<String>();
public void add() {
list.add("zjl");
}
public int size() {
return list.size();
}
public static void main(String[] args) {
final ListAddTest00 la = new ListAddTest00();
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
la.add();
 System .out.println("线程" + Thread.currentThread().getName() + "向集合中添加元素");
if (list.size() == 3) {
System.out.println("线程" + Thread.currentThread().getName() + "发出了通知");
}
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
while (true) {
if(list.size() == 3){
System.out.println("线程" + Thread.currentThread().getName() + "收到了通知");
break;
}
}
// throw new RuntimeException();
}
}, "t2");
t2. start ();
t1.start();
}
}

 

在上面这个程序中,也是实现了线程间的通信,只不过是通过不断的 轮询 来实现的,运行结果如下:

面试问题一:用线程的等待/通知机制来改造,怎么做?

用wait()/notify()改造后代码如下:

public class ListAddTest01 {
private static volatile List list = new ArrayList<String>();
public void add(){
list.add("zjl");
}
public int size(){
return list.size();
}
public static void main(String[] args) {
final ListAddTest01 la = new ListAddTest01();
final Object  lock  = new Object();
Thread t1 = new Thread(new Runnable() {
public void run() {
 synchronized  (lock) {
for(int i=0; i<5; i++){
la.add();
System.out.println("线程"+Thread.currentThread().getName()+"向集合中添加元素");
if(list.size() == 3){
lock.notify();
System.out.println("线程"+Thread.currentThread().getName()+"发出了通知");
}
}
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
synchronized (lock) {
if(list.size()!=3){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程"+Thread.currentThread().getName()+"收到了通知");
//throw new RuntimeException();
}
}
}, "t2");
t2.start();
t1.start();
}
}

 

此时不需要轮询,也实现了线程间的通信,运行结果如下:

问题二:这种方法有什么弊端吗?

答:有,因为对象的notify()方法发出了通知,但是没有释放锁,所以还要等到线程t1执行完,线程t2才能执行。

问题三:那有什么好的办法避免这种弊端?

答:用线程安全工具类CountDownLatch的countDown()方法和await()方法来实现,代码如下:

public class ListAddTest02 {
private static volatile List list = new ArrayList<String>();
public void add(){
list.add("zjl");
}
public int size(){
return list.size();
}

public static void main(String[] args) {
final ListAddTest02 la = new ListAddTest02();
final CountDownLatch latch = new CountDownLatch(1);
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i=0; i<5; i++){
la.add();
System.out.println("线程"+Thread.currentThread().getName()+"向集合中添加元素");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(list.size() == 3){
latch.countDown();
System.out.println("线程"+Thread.currentThread().getName()+"发出了通知");
}
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
if(list.size()!=3){
try {
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("线程"+Thread.currentThread().getName()+"收到了通知");
}
}, "t2");
t2.start();
t1.start();
}
}

 

运行结果如下:

文章来源:智云一二三科技

文章标题:Java多线程中的等待/通知机制

文章地址:https://www.zhihuclub.com/180665.shtml

关于作者: 智云科技

热门文章

网站地图