A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘海源 中级黑马   /  2012-7-23 19:24  /  1144 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class ThreadDemo2 {
        public static void main(String[] args) {
                number n=new number();
                Add a=new Add(n);
                Delete d=new Delete(n);
                Thread t1=new Thread(a);
                Thread t2=new Thread(a);
                Thread t3=new Thread(d);
                Thread t4=new Thread(d);
                t1.start();
                t2.start();
                t3.start();
                t4.start();
        }

}
class number
{
        private int j=0;
        public number(){}
        public number(int j)
        {
                this.j=j;
        }

        public int getJ() {
                return j;
        }

        public void setJ(int j) {
                this.j = j;
               
        }
}
class Add implements Runnable
{
  private number n;
  private int j;
  public Add(number n)
  {
          this.n=n;
  }
   public void run()
   {
           while(true)
           {
                   synchronized (this) {
                   j=n.getJ();
                }      System.out.println(Thread.currentThread().getName()+"  ***"+j++);
           }
   }
}
class Delete implements Runnable
{
          private number n;
          private int j;
          public Delete(number n)
          {
                  this.n=n;
          }
           public void run()
           {
                   while(true)
                   {
                           synchronized (this) {
                           j=n.getJ();
                           System.out.println(Thread.currentThread().getName()+"  ***"+j--);
                        }     
                   }
           }
}
//自己写的代码但是没理想的效果,j++和j--怎么都一样??

2 个回复

倒序浏览
楼主能把自己的想法用代码实现是个好习惯。。。
但是提问题要突出重点
最起码你该把你程序的功能说说吧,何况你还没加注释
你程序里面的变量j是私有的,而且你也提供了赋值和获取的方法
可是你的线程里一直都是在获取j的值而且获取后就立马赋给了成员变量j
你一直加加减减的都是成员变量的j的值
而且每次打印之前都又获取了一下原来的j的值
当然j++和j--没有效果了
希望对你有所帮助。。。

评分

参与人数 1技术分 +1 收起 理由
田向向 + 1 说的有道理,鼓励一下

查看全部评分

回复 使用道具 举报
while(true)
                    {
                            synchronized (this) {
                            j=n.getJ();
                            System.out.println(Thread.currentThread().getName()+"  ***"“)
                         }     
                    }
每次循环完了之后,都还会再走j=n.getJ();所以每次循环后都会给j从新赋值,并且值都是n.getJ(),j++和j--都是先使用,后赋值。所以值一直都一样
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马