JAVA线程通信之生产者与消费者

时间:2022-11-25 14:30:33
package cn.test.hf.test3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; public class FactoryUtils { private Resource resource;
private int producerId = 1; // 可重入锁
ReentrantLock lock = new ReentrantLock();
Condition ProducersCondition = lock.newCondition(); Condition customerLockCondition = lock.newCondition(); FactoryUtils() { resource = new Resource(); resource.setId(0);
resource.setFlag(true);
} /**
* 生产
*/
public void ProducerResource() { lock.lock();
// 使用锁机制
try { while (true) { while (!resource.isFlag()) { // 还未消费,将线程等待
System.out.println("生产者等待");
// 使用condition通知同组的等待
ProducersCondition.await();
} // 生产
resource.setId(producerId++);
resource.setFlag(false);
System.out.println("生产者线程" + Thread.currentThread().getName() + "生产了ID为" + resource.getId() + "的产品");
// 延时一秒好看结果
Thread.sleep(1000);
// 生产完后通知消费者线程
System.out.println("通知消费者");
customerLockCondition.signalAll();
}
} catch (Exception e) { e.printStackTrace();
} finally { // 释放锁
lock.unlock();
}
} /**
* 生产
*/
public synchronized void customer() { lock.lock();
try {
while (true) { // 消费者等待
while (resource.isFlag()) { customerLockCondition.await();
} // 设置为已消费
resource.setFlag(true);
System.out.println("消费者线程" + Thread.currentThread().getName() + "消费了ID为" + resource.getId() + "的产品");
// 延时一秒好看结果
Thread.sleep(1000);
// 消费完后通知生产者线程生产
System.out.println("通知生产者");
ProducersCondition.signalAll();
}
} catch (Exception e) { e.printStackTrace();
} finally {
lock.unlock();
}
}
}