kuop4wn
2015-12-14 13:46
采纳率: 50%
浏览 1.4k
已采纳

Java关于线程同步的问题

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());
}
}
}
感觉代码没错啊 但是结果总是不正确图片说明

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

相关推荐 更多相似问题