public class TestThread {
public static void main(String[] args) {
Data data=new Data();
new Thread(new DataProvider(data)).start();
new Thread(new DataConsumer(data)).start();
}
}
class Data{
private String title;
private String note;
private boolean flag=false;
public synchronized void get(){
if(flag==false){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.title+="="+this.note);
this.flag=false;
super.notify();
}
public synchronized void set(String title,String note){
if(flag==true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title=title;
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.note=note;
this.flag=true;
super.notify();
}
}
class DataProvider implements Runnable{
private Data data;
public DataProvider(Data data){
this.data=data;
}
@Override
public void run() {
for(int x=0;x<50;x++){
if(x%2==0){
this.data.set("jk","666");
}else{
this.data.set("xx","555");
}
}
}
}
class DataConsumer implements Runnable{
private Data data;
public DataConsumer(Data data){
this.data=data;
}
@Override
public void run() {
for(int x=0;x<50;x++){
this.data.get();
}
}
}