日期:2014-05-20 浏览次数:20723 次
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();
}
}