本帖最后由 左华清 于 2012-2-23 11:40 编辑
想实现"zhangshan:male","lisi:female"
老报错,请大家指点下!
package cn.itcast.threadtest;
public class ThreadCommunation {
public static void main(String[]args){
Q q=new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
class Producer implements Runnable{
Q q;
public Producer(Q q){
this.q=q;
}
public void run(){
int i=0;
while(true){
synchronized(q){
if(q.bFull){
try{wait();}catch(Exception e){};
}
if(i==0){
q.name="zhangshan";
try{Thread.sleep(1);}catch(Exception e){};
q.sex="male";
}else{
q.name="lisi";
q.sex="female";
}
q.bFull=true;
notify();
}
i=(i+1)%2;
}
}
}
class Consumer implements Runnable{
Q q;
public Consumer(Q q){
this.q=q;
}
public void run(){
while(true){
synchronized(q){
if(!q.bFull){
try{wait();}catch(Exception e){};
}
System.out.print(q.name);
System.out.println(":"+q.sex);
q.bFull=false;
notify();
}
}
}
}
class Q{
public String name="unknown";
public String sex="unknown";
public boolean bFull=false;
} |