package thread;
public class Buffer {
int value;
boolean flag = false;
//synchronized同步化
public synchronized int getValue(int value){
if(flag==false){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(" 取得值"+value);
flag=false;
notify();
return value;
}
public synchronized void setValue(int value){
if(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.value = value;
System.out.println("设置值"+value);
flag=true;
notify();
}
}
package thread;
public class SetThread extends Thread{
Buffer buffer;
public SetThread(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for(int i=0; i<30; i++){
buffer.setValue(i);
}
}
}
package thread;
public class GetThread extends Thread{
Buffer buffer;
public GetThread(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for(int i=0; i<30; i++){
buffer.getValue(i);
}
}
}
package thread;
public class BufferTest {
public static void main(String[] args) {
Buffer buf = new Buffer();
SetThread st = new SetThread(buf);
GetThread gt = new GetThread(buf);
st.start();
gt.start();
}
}
package thread;public class Buffer { int value; boolean flag = false; //synchronized同步化 public synchronized int getValue(int value){ if(flag==false){ try { wait(); } catch (Interru...