Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2293364
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Java

2014-11-10 20:12:48


  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. }


阅读(5990) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~