用java写一个多线程程序,其中两个对一个变量加1,另两个对一个变量减1

public class addSubThread {
    /*
         * 题目:用JAVA写一个多线程程序,写四个线程,其中二个对一个变量加1,另外二个对一个变量减1
         * 两个问题:
         * 一、线程同步--synchronized
         * 二、线程之间如何共享同一个j变量--内部类
         */
    private int i = 100;
    
    /** 加一方法 */
    public synchronized void addOne(){
         i++;
         System.out.println(Thread.currentThread().getName() + "----> addOne:" + i);
    }
    
    /** 减一方法 */
    public synchronized void subOne(){
         i--;
         System.out.println(Thread.currentThread().getName() + "----> subOne:" + i);
    }
    
     class addThread implements Runnable{java

        @Override
        public void run() {
            addOne();
        }
     }多线程

     class subThread implements Runnable{ide

        @Override
        public void run() {
            subOne();
        }
     }
    
     public static void main(String[] args) {
         addSubThread re = new addSubThread();
         addThread aT = re.new addThread();
         subThread sT = re.new subThread();
         for(int i=0; i<2; i++){
             Thread addThread = new Thread(aT);
             addThread.start();
             Thread subThread = new Thread(sT);
             subThread.start();
         }
    }
     
}
用java写一个多线程程序,其中两个对一个变量加1,另两个对一个变量减1.net

相关文章
相关标签/搜索