品易云推流 关闭
文章详情页
文章 > java基础 > java中使用notifyall

java中使用notifyall

头像

小妮浅浅

2021-01-08 14:27:122622浏览 · 0收藏 · 0评论

有些人觉得一个个的唤醒线程比较麻烦,这时候使用notifyall是一个不错的选择。从名称上可以看出,它是notify方法的升级,能够对所有的线程进行唤醒,解除线程的阻塞状态。下面我们就notifyall的概念、语法、参数、返回值、使用注意进行分享,然后在实例中唤醒所有线程。

1.概念

对象调用该方法时,队列中所有处于阻塞状态的线程不再阻塞(当然,哪一个线程先运行由系统决定)

2.语法

public final void notifyAll()

3.参数

4.返回值

没有返回值

5.使用注意

唤醒的是notify之前wait的线程,对于notify之后的wait线程是没有效果的。

6.实例

class myThread implements Runnable{
    private boolean flag ;
    private Object object ;
 
    myThread(boolean flag, Object o){
        this.flag = flag;
        this.object = o;
    }
    private void waitThread(){
        synchronized (object) {
            System.out.println(Thread.currentThread().getName() + "wait begin...");
            try {
                object.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "wait end...");
        }
    }
    private void notifyThread(){
        synchronized (object) {
            System.out.println(Thread.currentThread().getName() + "notify begin...");
            object.notify();
            System.out.println(Thread.currentThread().getName() + "notify end...");
        }
    }
    @Override
    public void run() {
        if(flag){
            waitThread();
        }else {
            notifyThread();
        }
    }
}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        myThread mt2 = new myThread(false,object);
        Thread thread1 = new Thread(mt2,"线程B ");
        for (int i = 0;i<10;i++) {
            myThread mt = new myThread(true,object);
            Thread thread = new Thread(mt,"线程A "+i);
            thread.start();
        }
        Thread.sleep(1000);
        thread1.start();
    }
}

以上就是java中使用notifyall的方法,根据以上代码,我们可以对程序中等待的线程全部唤醒,操作上比较简单和方便,学会后赶快试试吧。

关注

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

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

底部广告图