用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. }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值