日期:2014-05-20 浏览次数:20925 次
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();
            }    
        }
    }
}