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

  1. public class IncDecThread {

  2.     private int j=10;
  3.     
  4.     /*
  5.      * 题目:用JAVA写一个多线程程序,写四个线程,其中二个对一个变量加1,另外二个对一个变量减1
  6.      * 两个问题:
  7.      * 1、线程同步--synchronized
  8.      * 2、线程之间如何共享同一个j变量--内部类
  9.      */
  10.     public static void main(String[] args) {
  11.         IncDecThread incDec=new IncDecThread();
  12.         Inc inc=incDec.new Inc();
  13.         Dec dec=incDec.new Dec();
  14.         for(int i=0;i<2;i++){
  15.             Thread thread=new Thread(inc);
  16.             thread.start();
  17.             thread=new Thread(dec);
  18.             thread.start();
  19.         }
  20.     }

  21.     public synchronized void inc(){
  22.         j++;
  23.         System.out.println(Thread.currentThread().getName()+"-inc:"+j);
  24.     }
  25.     public synchronized void dec(){
  26.         j--;
  27.         System.out.println(Thread.currentThread().getName()+"-dec:"+j);
  28.     }
  29.     
  30.     class Inc implements Runnable{
  31.         public void run(){
  32.             for(int i=0;i<20;i++){
  33.                 inc();
  34.             }
  35.         }
  36.     }
  37.     class Dec implements Runnable{
  38.         public void run(){
  39.             for(int i=0;i<20;i++){
  40.                 dec();
  41.             }
  42.         }
  43.     }
  44. }