首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

synchronized 有关问题

2012-04-18 
求一个 synchronized 问题Java codepublic class TestThread {static int aa 0public static void main

求一个 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);            //}    }} 

热点排行