您的位置:程序门 -> java -> j2ee / ejb / jms



各们大人帮个忙


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


各们大人帮个忙
发表于:2008-01-24 20:06:21 楼主
我做了个线程类不知道加了synchronized就不循环啦。不加它的时候是可以循环的。各位给帮忙看下。下面是程序。
class   producer   implements   runnable
{
      input   p=null;  
      public   producer(input   p)
      {
      this.p=p;
      }
      public   void   run()
      {
      int   i=0;
      while(true)
      {
      synchronized(p)
              {
              if(i==0)
                  {
                  p.name="张孝祥";
                  try
                    {
                  thread.sleep(10);
                    }
                  catch(exception   e)
                    {
                  system.out.println(e.getmessage());
                    }
                  p.sex="男";
                  }
              else
                  {
                  p.name="张柏芝";
                  p.sex="女";
                  }
     
              }
      i=(i+1)%2;
      }
     
      }
}
class   input
{
          string   name="";
          string   sex="";
}
class   consumer   implements   runnable
{
input   p=null;
public   consumer(input   p)
{
this.p=p;
}
public   void   run()
{
while(true)
{
synchronized(p)
{system.out.println(p.name+"--------> "+p.sex);}
}
}
}

public   class   threadcommunation   {

/**
  *   @param   args
  */
public   static   void   main(string[]   args)   {
//   todo   auto-generated   method   stub
            input   p=new   input();
            /*producer   t1=new   producer(p);
            thread   tt1=new   thread(t1);
            tt1.start();
            consumer   t2=new   consumer(p);
            thread   tt2=new   thread(t2);
            tt2.start();*/
            new   thread(new   producer(p)).start();
            new   thread(new   consumer(p)).start();
}

}
发表于:2008-01-24 20:49:541楼 得分:0
sleep()   这个方法好象不会释放线程锁

应该   在线程中用   wait(),notify()
发表于:2008-01-24 21:10:252楼 得分:0
和线程锁没关系吧。我就加了一个synchronized以后他就不能循环啦。去了那句就能。


快速检索

最新资讯
热门点击