您的位置:首页 > 编程语言 > Java开发

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

2013-03-06 17:28 302 查看
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();
}
}
}

很多东西都记不太清楚了这几天翻来看了下,温故而知新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JavaThread
相关文章推荐