一段代码展示notifyAll和notify的区别

最近要找工作,又把之前多线程的东西捞出来看看。

public class testOptional {

    public static class Wait {
        private volatile Integer counter = 0;
        private String name = null;
        public Wait(int counter, String name) {
            this.counter = counter;
            this.name = name;
        }

        public synchronized void doSomthing() {
            System.out.println(Thread.currentThread().getName() + "start");
            int tempcounter = --counter;
            if (tempcounter <= 0) {
//                customizedNotifyAll();
               notify();
            } else {
                if (tempcounter > 0) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "-<" + name + tempcounter + ">" + "will invoke WAIT()");
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        notifyAll();
                    }
                    System.out.println(Thread.currentThread().getName() + "-<" + name + tempcounter + ">" + "has been ACTIVED");
                }
            }
        }

        public void customizedNotifyAll() {
            notifyAll();
            System.out.println(Thread.currentThread().getName() + "-<" + name + counter + ">" + "::" + "INVOKED NOTIFYALL() AND FINISHED");
        }
    }

    static class TestThread implements Runnable {
        private Wait wait;
        public TestThread(Wait wait) {
            this.wait = wait;
        }

        public void run() {
            wait.doSomthing();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        Wait wait = new Wait(4, "test");

        Thread testThread1 = new Thread(new TestThread(wait));

        Thread testThread2 = new Thread(new TestThread(wait));

        Thread testThread3 = new Thread(new TestThread(wait));

        Thread testThread4 = new Thread(new TestThread(wait));

        testThread1.start();

        Thread.sleep(10);

        testThread2.start();

        Thread.sleep(10);

        testThread3.start();

        Thread.sleep(10);

        testThread4.start();

    }

}

代码是从网上一人的博客上改的,原代码有些问题
附上运行结果
notifyAll()

微信截图_20170413161237.png

notify()

微信截图111.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 写在前面的话: 这篇博客是我从这里“转载”的,为什么转载两个字加“”呢?因为这绝不是简单的复制粘贴,我花了五六个小...
    SmartSean阅读 4,792评论 12 45
  • 一、进程和线程 进程 进程就是一个执行中的程序实例,每个进程都有自己独立的一块内存空间,一个进程中可以有多个线程。...
    阿敏其人阅读 2,625评论 0 13
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 文 | 玉茗公子 在办理员工入职的时候,总会遇到这样的情况。员工A说:“离职证明没有开!“员工B说:“离职证明不见...
    玉茗公子阅读 9,862评论 0 7
  • AlertDialog(对话框) 1.基本使用流程 Step 1:创建AlertDialog.Buil...
    jadefly阅读 342评论 0 0