package ing;
class Person{
private String name;
private String sex;
public boolean isempty =true;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex=sex;
}
public void set(String name,String sex) throws InterruptedException{
synchronized (this) {
while(isempty){
System.out.println("kaishi wait");
this.notifyAll();
this.name=name;
this.sex=sex;
isempty=false;System.out.println("isempty zhiwei false");
this.wait();
break;
}
}
}
public void get() throws InterruptedException{
synchronized (this) {
System.out.println("isempty "+isempty);
while(!isempty){
System.out.println("get fangfa tongbu nei");
this.notifyAll();
System.out.println("xingming"+getName()+", "+"xingbie"+getSex());
isempty=true;
this.wait();
break;
}
}
}
}
class Consumer implements Runnable{
private Person p;
public Consumer(Person p){
super();
this.p=p;
}
public void run() {
System.out.println("consumer run fangfa");
for(int i=0;i<100;i++){
try {
p.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
private Person p;
public Producer(Person p) {
super();
this.p=p;
System.out.println("producer gouzao");
}
@Override
public void run() {
System.out.println("producer run fangfa");
for(int i=0;i<100;i++){
if(i%2==0){
try {
System.out.println("set liuzhao nan");
p.set("刘钊", "男");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{try {
System.out.println("set zhangzetian nv");
p.set("章泽天", "女");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
}}
public class shengchanxiaofei {
public static void main(String[] args) {
Person p =new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
class Consumer implements Runnable{
private Person p;
public Consumer(Person p){
super();
this.p=p;
}
public void run() {
System.out.println("consumer run fangfa");
for(int i=0;i<100;i++){
try {
p.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
private Person p;
public Producer(Person p) {
super();
this.p=p;
System.out.println("producer gouzao");
}
Thread t = Thread.currentThread();
@Override
public void run() {
System.out.println("producer run fangfa");
for(int i=0;i<100;i++){
if(i%2==0){
try {
System.out.println("set liuzhao nan");
p.set("刘钊", "男");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{try {
System.out.println("set zhangzetian nv");
p.set("章泽天", "女");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
}}
public class shengchanxiaofei {
public static void main(String[] args) {
Person p =new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
ok,你是不是想达到这个效果,自己看看问题出在哪里 |