日期:2014-05-20  浏览次数:20927 次

求一个 synchronized 问题
Java code

public class TestThread {

    static int aa = 0;

    public static void main(String[] args) {

        Threadd a = new TestThread().new Threadd();
        Threadd b = new TestThread().new Threadd();
        Threadd c = new TestThread().new Threadd();
        a.start();
        b.start();
        c.start();

    }

    class Threadd extends Thread {

        @Override
        public void run() {
            printt();
        }
    }

    // 为什么这个地方不能锁定呢?
    synchronized void printt() {
        this.aa = (this.aa + 1);
        System.out.println(this.aa);
    }

}

为什么这么做就不可以得到1 2 3的输出呢 ?

------解决方案--------------------
你new了仨TestThread(),各自操作各自的aa,肯定同步不了啊。内部类对象与它对应的外部对象关联,和别的没关系。
------解决方案--------------------
synchronized 修饰方法,锁的是调用该方法的对象。
------解决方案--------------------
调用静态变量用类名的吧,
aa是静态变量,要输出1 2 3可以讲print声明为static或者用synchronized(TestThread.class)来达到同步修改静态变量的目的。还有为啥不要静态内部类,让代码看上去简洁一些。
比如:
Java code

public class TestThread {

    static int aa = 0;

    public static void main(String[] args) {
        Threadd a = new TestThread().new Threadd();
        Threadd b = new TestThread().new Threadd();
        Threadd c = new TestThread().new Threadd();
        a.start();
        b.start();
        c.start();
    }

    class Threadd extends Thread {
        @Override
        public void run() {
            printt();
        }
    }

    // 为什么这个地方不能锁定呢?
    static synchronized void printt() {
        //synchronized (TestThread.class) {
            aa = (aa + 1);
            System.out.println(aa);    
        //}
    }
}