这个是以前以前写的一个通过生产消费模式反应线程同步的一个案例

来源:互联网 发布:林建华 北大 知乎 编辑:程序博客网 时间:2024/04/29 14:18
import java.util.Random;


public class Demo13 {
public static void main(String[] args) {
final Oprations ops = new Oprations();
new Thread(new Runnable() {


@Override
public void run() {
//只生产5个
for (int i = 1; i <= 5; i++) {
ops.send();
}
}
}).start();
Thread t = new Thread(new Runnable() {

@Override
public void run() {
while(true){
//不管有没有生产都一直消费,因为只有生产了才能消费
ops.rec();
}
}
});
t.setDaemon(true);
t.start();
}
}


class Oprations{
private boolean flag;
int theValue;


/** 生产者 */
public void send() {
synchronized (this) {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
theValue = new Random().nextInt(1000);
System.out.println("send the value is:" + theValue);
flag = true;
this.notify();
}
}


/** 消费者 */
public void rec() {
synchronized (this) {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("receive the value is:" + theValue);
flag = false;
this.notify();
}
}

}

很多东西都记不太清楚了这几天翻来看了下,温故而知新