美文网首页
一段代码展示notifyAll和notify的区别

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

作者: c7d122ec46c0 | 来源:发表于2017-04-13 16:44 被阅读0次

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

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

相关文章

网友评论

      本文标题:一段代码展示notifyAll和notify的区别

      本文链接:https://www.haomeiwen.com/subject/senbattx.html