日期:2014-05-20  浏览次数:20775 次

各们大人帮个忙
我做了个线程类不知道加了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();
}

}


------解决方案--------------------
SLEEP() 这个方法好象不会释放线程锁

应该 在线程中用 wait(),notify()
------解决方案--------------------
和线程锁没关系吧。我就加了一个synchronized以后他就不能循环啦。去了那句就能。