栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java中使用notifyall

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java中使用notifyall

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/15212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号