关于wait(),notify(),notifyAll()

2017-11-06  本文已影响0人  做个文艺的程序猿

这三个方法,必须在synchronized代码里执行的例子

 class A {
    public void waitMethod(Object obj) {try {
            synchronized (obj) {
                obj.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void notifyMethod(Object obj) {
        synchronized (obj) {
            obj.notify();
        }
    }
    public synchronized void waitMethod2() {
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void notifyMethod2() {
        this.notify();
    }
    public static synchronized void waitMethod3() {
        try {
            A.class.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static synchronized void notifyMethod3() {
        A.class.notify();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读