package com.test.thread;
public class Home {
public static void main(String[] args) {
ShareRegion share = new ShareRegion();
new Thread(new Producer(share)).start();
new Thread(new Consumer(share)).start();
}
}
package com.test.thread;
public class ShareRegion {
private String name;
private String sex;
boolean isProduce = true;
synchronized public void setterData(String name,String sex) {
try {
if (!isProduce) {
this.wait();
}
this.name = name;
Thread.sleep(10);
this.sex = sex;
isProduce = false;
this.notifyAll();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
synchronized public void getterData() {
try {
if(isProduce) {
this.wait();
}
System.out.println(this.name+"/"+this.sex);
isProduce = true;
this.notifyAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.test.thread;
import java.lang.Runnable;
public class Producer implements Runnable{
private ShareRegion share = null;
public Producer(ShareRegion share){
this.share = share;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (i%2 == 0) {
share.setterData("春哥", "男");
}else {
share.setterData("凤姐", "女");
}
}
}
}
package com.test.thread;
import java.lang.Runnable;
public class Consumer implements Runnable{
private ShareRegion share = null;
public Consumer(ShareRegion share){
this.share = share;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 50; i++) {
share.getterData();
}
}
}