java中使用notifyall

2026-01-29 0 50,090

有些人觉得一个个的唤醒线程比较麻烦,这时候使用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的方法,根据以上代码,我们可以对程序中等待的线程全部唤醒,操作上比较简单和方便,学会后赶快试试吧。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 java教程 java中使用notifyall https://www.zhiup.top/11071.html

相关