线程同步 wait 和 notify 使用例子

如果需要统计区间[0, 1000]范围内偶数的个数,可以使用如下代码:

public class Test {

    private static int counter = 0;

    private static class CountRunnable implements Runnable {
        public void run() {
            for (int i = 0; i < 10; ++i) {
                if (i % 2 == 0) {
                    counter += 1;
                }
            }
        }
    }

    public static void main(String []args) throws InterruptedException {
        Runnable r = new CountRunnable();
        Thread t = new Thread(r);
        t.start();
        System.out.println("counter=" + counter);
    }
}

运行之后发现结果总是 0,这是由于线程启动 t 启动之后,run 方法还没执行之前,主线程就已经执行完成了;为了解决这个问题,可以在 t.start() 之后添加 sleep 来解决这个问题。

虽然通过 sleep 可以解决这个问题,但是解决方案不够灵活和优雅,更好的方法是通过线程之间的同步机制来彻底解决,可以在 t.start() 之后添加如下代码:

synchronized (t) {
    t.wait();
}

这段代码的作用在于,在 t.start() 调用 notify() 之前,主线程一直处于 wait 的状态。

 

猜测应该是 t.start() 里面调用了 notify() 方法,为了验证,可以在 synchroized 上面加上 sleep(), 这样一来,t.start() 执行完成并且 notify() 方法已经调用完成之后,t.wait() 还没有被执行,等执行到 t.wait() 的时候,程序就会死等在这里,因为已经没有 notify() 调用了。

posted @ 2015-10-09 17:19  cbffr  阅读(413)  评论(0编辑  收藏  举报