• 技术文章 >java >java基础

    java中使用notifyall

    小妮浅浅小妮浅浅2021-01-08 14:27:12原创2739

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

    1.概念

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

    2.语法

    1

    public final void notifyAll()

    3.参数

    4.返回值

    没有返回值

    5.使用注意

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

    6.实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    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的方法,根据以上代码,我们可以对程序中等待的线程全部唤醒,操作上比较简单和方便,学会后赶快试试吧。

    专题推荐:java notifyall
    上一篇:java notify()的唤醒 下一篇:sleep在java中的实现

    相关文章推荐

    • 线程在java中的通信• thread类在java线程中的使用• java守护线程应用• java中Thread的停止• java中wait是什么意思• java notify()的唤醒

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网