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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yangshang1 中级黑马   /  2012-3-29 14:23  /  1311 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。

2 个回复

倒序浏览


public class ThreadTest1{
         
    private int j;

    public static void main(String args[]){

    ThreadTest1 tt=new ThreadTest1();

    Inc inc=tt.new Inc();

    Dec dec=tt.new Dec();

    for(int i=0;i<2;i++){

    Thread t=new Thread(inc);

    t.start();

    t=new Thread(dec);

    t.start();

    }

    }

    private synchronized void inc(){

    j++;

    System.out.println(Thread.currentThread().getName()+"-inc:"+j);

    }

    private synchronized void dec(){

    j--;

    System.out.println(Thread.currentThread().getName()+"-dec:"+j);

    }

    class Inc implements Runnable{

    public void run(){

    for(int i=0;i<100;i++){

    inc();

    }

    }

    }

    class Dec implements Runnable{

    public void run(){

    for(int i=0;i<100;i++){

    dec();

    }

    }

    }

    }


已解决共享
回复 使用道具 举报
这是我根据“生产者和消费者”例子编写的,这个例子课件里有,你可以看看完之后自己写,我写这个只是交流交流,这个程序还有很多不合理的地方,需要改进,但由于本人技术有限只能写成这样了,没有写注释,你看了那个例子之后就很轻松的看懂了。
class Res
{
   private int j;
   private boolean flag=false;
   public synchronized void add()
     {
      while(flag)
          try
            {
             wait();
             }
           catch(Exception e)
            {  }
       System.out.println("j++:"+j++);
        flag=true;
        this.notifyAll();
      }
    public synchronized void sub()
     {
       while(!flag)
          try
            {
             wait();
             }
           catch(Exception e)
            {  }
       System.out.println("j--:"+j--);
         flag=false;
        this.notifyAll();
      }
}
class Zz implements Runnable
{
     private Res z;
      Zz(Res z)
      {
         this.z=z;
       }
     public void run()
     {   
        while(true)
         {
          z.add();
          }
      }
}
class Zj implements Runnable
{
     private Res j;
      Zj(Res j)
      {
        this.j=j;
        }
     public void run()
     {  
         while(true)
         {
         j.sub();
         }
      }
}
class Demotest
{
  public static void main(String[] args)
     {
         Res r=new Res();
         Zz sum= new Zz(r);
         Thread t1=new Thread(sum);
         Thread t2=new Thread(sum);
         t1.start();
          t2.start();
         Zj sub1= new Zj(r);
         Thread  t3=new Thread(sub1);
         Thread  t4=new Thread(sub1);
          t3.start();
          t4.start();
      }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马