读书人

求高人指点是否是死锁的有关问题~怎么

发布时间: 2011-12-13 21:22:18 作者: rapoo

求高人指点是否是死锁的问题~怎么运行为空呢
package lesson5;

class Producer implements Runnable
{
Q q;
public Producer (Q q)
{
this.q=q;
}

public void run()
{
int i =0;

while (true)
{
if(i==0)

q.put("111111","man");

else

q.put("22222", "woman");


i=(i+1)%2;
}


}
}

class Consumer implements Runnable
{
Q q;

public Consumer (Q q)
{
this.q=q;
}

public void run()
{

while (true)

{

q.get();
}

}

}

class Q
{
String name="unknow";
String sex="unknow";
boolean bl;


public synchronized void put(String name,String sex)
{

if(bl);
try{wait();}catch (Exception e){}

this.name=name;

try {Thread.sleep(500);} catch (InterruptedException e) {}
this.sex=sex;
bl=true;
notify();
}
public synchronized void get ()
{

if(!bl);
try{wait();}catch (Exception e){}
System.out.print(name);

System.out.println(":"+sex);
bl=false;
notify();
}
}


class Threadyunxing
{
public static void main(String [] args)
{
Q q=new Q();
new Thread ( new Producer(q)).start();
new Thread ( new Consumer(q)) .start();

}
}


[解决办法]

Java code
 
package lesson5;

class Producer implements Runnable
{
Q q;
public Producer (Q q)
{
this.q=q;
}

public void run()
{
int i =0;

while (true)
{
if(i==0)

q.put("111111","man");

else

q.put("22222", "woman");


i=(i+1)%2;
}


}
}

class Consumer implements Runnable
{
Q q;

public Consumer (Q q)
{
this.q=q;
}

public void run()
{

while (true)

{

q.get();
}

}

}

class Q
{
String name="unknow";
String sex="unknow";
boolean bl;


public synchronized void put(String name,String sex)
{

if(bl);
try{wait();}catch (Exception e){}

this.name=name;

try {Thread.sleep(500);} catch (InterruptedException e) {}
this.sex=sex;
bl=true;
notify();
}
public synchronized void get ()
{

if(!bl); //此处多了一个分号,去掉就可以了
try{wait();}catch (Exception e){}
System.out.print(name);

System.out.println(":"+sex);
bl=false;
notify();
}
}


class Threadyunxing
{
public static void main(String [] args)
{
Q q=new Q();
new Thread ( new Producer(q)).start();
new Thread ( new Consumer(q)) .start();

}
}

读书人网 >J2SE开发

热点推荐