通过生产消费模式反应线程同步
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 receive() {
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();
}
}
}
以前学习时做的一些东西,这个是通过生产消费者模式在反应线程同步 thread
补充:Java , Java SE