package com.thread.tongbu;
public class Buffer {
private int value;
private boolean isEmpty=true;
public synchronized void put(int i) {
while(!this.isEmpty)
try {
this.wait();
} catch (InterruptedException e) {}
this.value=i;
this.isEmpty=false;
this.notify();
}
public synchronized int get() {
while(this.isEmpty)
try {
this.wait();
} catch (InterruptedException e) {}
this.isEmpty=true;
this.notify();
return this.value;
}
public static void main(String args[]) {
Buffer buffer=new Buffer();
(new SendThread(buffer)).start();
(new ReceiveThread(buffer)).start();
}
}
public class SendThread extends Thread {
private Buffer buffer;
public SendThread(Buffer buffer){
this.buffer=buffer;
}
public void run(){
for(int i=1;i<5;i++){
buffer.put(i);
System.out.println(this.getClass().getName()+"put:"+i);
}
}
}
public class ReceiveThread extends Thread {
private Buffer buffer;
public ReceiveThread(Buffer buffer) {
this.buffer=buffer;
}
public void run() {
for(int i=1;i<5;i++){
System.out.println("\t\t\t\t"+this.getClass().getName()+"get:"+buffer.get());
}
}
}
感觉代码没错啊 但是结果总是不正确