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

求教一个简单的多线程小程序
Java code

public class TestThread {
    private int j;
    
    public static void main(String[] args) {
        TestThread t = new TestThread();
        Inc inc = t.new Inc();
        Dec dec = t.new Dec();
        for(int i=0;i<2;i++){
            Thread thread = new Thread(inc);
            thread.start();
            thread = new Thread(dec);
            thread.start();
        }
    }
    
    private synchronized void inc() {
        j++;
        System.out.println(Thread.currentThread().getName()+"-inc:"+j);
    }
    
    private synchronized void dec() {
        j--;
        System.out.println(Thread.currentThread().getName()+"-dec:"+j);
    }
    //内部类
    class Inc implements Runnable {
        public void run() {
            for(int i=0;i<100;i++){
                inc();
            }
        }
    }
    class Dec implements Runnable {
        public void run() {
            for(int i=0;i<100;i++){
                dec();
            }    
        }
    }

}


代码如上,我想问一下“private synchronized void inc()”这里的synchronized锁住的是inc这个内部类对象,还是调用这个内部类的TestThread类的t对象?


------解决方案--------------------
synchronized默认的就是this, 这个方法在TestThread里面,所以是t.
------解决方案--------------------
探讨
synchronized默认的就是this, 这个方法在TestThread里面,所以是t.