class ConsumerProducerTester { //总控制
public static void main(String args[]){
Data kz=new Data();
Producer sc=new Producer(kz);
Consumer xf=new Consumer(kz);
sc.start() ;
xf.start() ;
}
}class Producer extends Thread{ //生产者
Data kz;
public Producer(Data kz) {
this.kz=kz;
} public void run(){
for(int i=0 ;i<1000;i++){
this.kz.put(i) ;
}
}}class Consumer extends Thread { //消费者 Data kz;
public Consumer(Data kz) {
this.kz=kz;
} public void run(){
for(int i=0;i<1000;i++){
System.out.println(kz.get() ) ;
}
}
}class Data {
private int val;
private boolean hasValue = true;
private Object o = new Object(); public int get(){
synchronized(o) {
if(hasValue){
System.out.println("get wait:");
try{ o.wait();}catch(Exception e){}
}
System.out.println("get wakeup");
hasValue = !hasValue;
o.notify();
return val;
}
} public void put(int i){
synchronized(o) {
if(!hasValue) {
System.out.println("put wait:");
try{ o.wait();}catch(Exception e){}
}
System.out.println("put wakeup");
hasValue = !hasValue;
val=i;
o.notify();
}
}
}
public static void main(String args[]){
Data kz=new Data();
Producer sc=new Producer(kz);
Consumer xf=new Consumer(kz);
sc.start() ;
xf.start() ;
}
}class Producer extends Thread{ //生产者
Data kz;
public Producer(Data kz) {
this.kz=kz;
} public void run(){
for(int i=0 ;i<1000;i++){
this.kz.put(i) ;
}
}}class Consumer extends Thread { //消费者 Data kz;
public Consumer(Data kz) {
this.kz=kz;
} public void run(){
for(int i=0;i<1000;i++){
System.out.println(kz.get() ) ;
}
}
}class Data {
private int val;
private boolean hasValue = true;
private Object o = new Object(); public int get(){
synchronized(o) {
if(hasValue){
System.out.println("get wait:");
try{ o.wait();}catch(Exception e){}
}
System.out.println("get wakeup");
hasValue = !hasValue;
o.notify();
return val;
}
} public void put(int i){
synchronized(o) {
if(!hasValue) {
System.out.println("put wait:");
try{ o.wait();}catch(Exception e){}
}
System.out.println("put wakeup");
hasValue = !hasValue;
val=i;
o.notify();
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货