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

2017-04-13  本文已影响0人  c7d122ec46c0

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

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
上一篇 下一篇

猜你喜欢

热点阅读