不带参数的wait()方法将一直保持等待,知道其他线程调用notify()方法将其唤醒。
public class SynchronizedBuffer{
private int buffer = -1;//定义缓冲区
private boolean occupied = false;//信号量,用于两线程同步
public synchronized void set(int value) {//该方法设置Bufer的值模拟生产者生产
//得到调用该方法当前线程的名字
String name = Thread.currentThread().getName();
while(occupied) {//occupied为True,表明已经生产但还么有消费
try {
System.err.println(name+"试图生产,但上一次生产还没有消费,等待消费!");
wait();//生产者线程等待
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
buffer = value;//消费者线程唤醒该线程后,可以生产
System.out.println(name+" 生产一个整数: "+buffer);
occupied = true;//表明已经生产,必须先消费才能生产
notify();//唤醒消费者线程
}
public synchronized int get() {//该方法得到Buffer的值,模拟消费者
String name = Thread.currentThread().getName();
while(!occupied) {//occupied为false,表明还没有生产,不能消费
try {
System.err.println(name+" 试图消费,但还没有生产,等待生产!");
wait();//消费者线程等待
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
occupied = false;//表明已经消费可以生产
System.out.println(name+" 消费一个整数:"+buffer);
notify();//唤醒生产者
return buffer;
}
}
public class Producer extends Thread{
private SynchronizedBuffer sharedBuffer;//生产者线程存放数据的空间
public Producer(SynchronizedBuffer sharedBuffer) {
super("生产者线程");
this.sharedBuffer = sharedBuffer;
}
public void run() {//线程启动后执行,模拟生产5个数
for(int count=1; count<6; count++) {
try {
Thread.sleep((int)(Math.random()*2000));//线程休眠
sharedBuffer.set(count);//生产一个数
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consumer extends Thread{
private SynchronizedBuffer sharedBuffer;//消费者线程消费数据空间
public Consumer(SynchronizedBuffer sharedBuffer) {
super("消费者线程");
this.sharedBuffer = sharedBuffer;
}
public void run() {//线程启动后执行,模拟消费5个整数
int sum = 0;
for(int count=1; count<6; count++){
try {
Thread.sleep((int)(Math.random()*2000));//线程休眠
sum += sharedBuffer.get();//消费一个数
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName()+"消费者的整数和: "+sum);
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("模拟生产者和消费者同步");
//生产者和消费者线程共享数据存储空间
SynchronizedBuffer sharedBuffer = new SynchronizedBuffer();
Producer producer = new Producer(sharedBuffer);//生产者线程
Consumer consumer = new Consumer(sharedBuffer);//消费者线程
producer.start();//启动生产者
consumer.start();//启动消费者
}
}