标签:++ 代码 pipe turn lin str data 使用 线程
常用的同步方法是采用信号或加锁机制,保证资源在任意时刻至多被一个线程访问。Java语言在多线程编程上实现了完全对象化,提供了对同步机制的良好支持。
在Java中一共有四种方法支持同步,其中前三个是同步方法,一个是管道方法。管道方法不建议使用,阻塞队列方法在之前已有描述,现只提供前两种实现方法。
- PipedInputStream/PipedOutputStream
public class Producer extends Thread { // 每次生产的产品数量
public Producer(Storage storage) {
public void produce(int num) {
public void setNum(int num) {
public Storage getStorage() {
public void setStorage(Storage storage) {
public class Consumer extends Thread { // 每次消费的产品数量
public Consumer(Storage storage) {
public void consume(int num) {
public void setNum(int num) {
public Storage getStorage() {
public void setStorage(Storage storage) {
public class Storage { // 仓库最大存储量
private final int MAX_SIZE = 100;
private LinkedList<Object> list = new LinkedList<Object>();
public void produce(int num) {
while (list.size() + num > MAX_SIZE) {
System.out.print("【要生产的产品数量】:" + num);
System.out.println(" 【库存量】:" + list.size() + " 暂时不能执行生产任务!");
list.wait();// 由于条件不满足,生产阻塞
} catch (InterruptedException e) {
for (int i = 1; i <= num; ++i) {
System.out.print("【已经生产产品数】:" + num);
System.out.println(" 【现仓储量为】:" + list.size());
public void consume(int num) {
while (list.size() < num) {
System.out.print("【要消费的产品数量】:" + num);
System.out.println(" 【库存量】:" + list.size() + " 暂时不能执行生产任务!");
} catch (InterruptedException e) {
for (int i = 1; i <= num; ++i) {
System.out.print("【已经消费产品数】:" + num);
System.out.println(" 【现仓储)量为】:" + list.size());
public LinkedList<Object> getList() {
public void setList(LinkedList<Object> list) {
public int getMAX_SIZE() {
public class Storage { // 仓库最大存储量
private final int MAX_SIZE = 100;
private LinkedList<Object> list = new LinkedList<Object>();
private final Lock lock = new ReentrantLock();
private final Condition full = lock.newCondition();
private final Condition empty = lock.newCondition();
public void produce(int num) {
while (list.size() + num > MAX_SIZE) {
System.out.print("【要生产的产品数量】:" + num);
System.out.println(" 【库存量】:" + list.size() + " 暂时不能执行生产任务!");
} catch (InterruptedException e) {
for (int i = 1; i <= num; ++i) {
System.out.print("【已经生产产品数】:" + num);
System.out.println(" 【现仓储量为】:" + list.size());
public void consume(int num) {
while (list.size() < num) {
System.out.print("【要消费的产品数量】:" + num);
System.out.println(" 【库存量】:" + list.size() + " 暂时不能执行生产任务!");
} catch (InterruptedException e) {
for (int i = 1; i <= num; ++i) {
System.out.print("【已经消费产品数】:" + num);
System.out.println(" 【现仓储)量为】:" + list.size());
public int getMAX_SIZE() {
public LinkedList<Object> getList() {
public void setList(LinkedList<Object> list) {
Java技术学习:如何保证同一资源被多个线程并发访问时的完整性?
标签:++ 代码 pipe turn lin str data 使用 线程
原文地址:https://www.cnblogs.com/qf-dd/p/10419872.html