java-四个线程修改一个变量

package 经典;

public class 四个线程 {
    
    private int j=10;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        四个线程 mainClass=new 四个线程();
        
        for(int i=2; i>0; i--)
        {
            Thread thread=new Thread(mainClass.new IncThread());
            thread.start();
            thread=new Thread(mainClass.new DecThread());
            thread.start();
        }

    }
    
    private synchronized void inc(){
        j++;
        System.out.println(Thread.currentThread().getName()+", j="+j);
    }
    
    private synchronized void dec(){
        j--;
        System.out.println(Thread.currentThread().getName()+", j="+j);
    }
    
    class IncThread implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            for(int i=20; i>0 ;i--)
                inc();
        }
        
    }
    
    class DecThread implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            for(int i=20; i>0 ;i--)
                dec();
        }
    }

}
原文地址:https://www.cnblogs.com/huangcongcong/p/4007776.html