Java_多线程_并发协作模型_生产者消费者模式_管程法

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 共享资源类
 */
class ShareData {
    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws Exception {
        lock.lock();
        try {
            //判断
            while (num != 0) {
                //等待 不生产
                condition.await();
            }
            //干活
            num++;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //通知唤醒
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void deIncrement() throws Exception {
        lock.lock();
        try {
            //判断
            while (num == 0) {
                //等待 不消费
                condition.await();
            }
            //消费
            num--;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //通知唤醒
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
/**
 * Description
 * 一个初始值为0的变量 两个线程交替操作 一个加1 一个减1来5轮
 *
 * @author veliger@163.com
 * @version 1.0
 * @date 2019-04-13 14:01
 **/
public class ProdConsumerTraditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();
        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    shareData.deIncrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();
    }
}



package cn.thread4;

/**
 * 并发协作模型
 * 生产者消费者实现方式之一
 * 管程法
 * 有缓冲容器,可以实现存量生产消费
 * @author Chill Lyn
 *
 */
public class PipelineMethod {
	public static void main(String[] args) {
		Buffer buffer = new Buffer();
		new Thread(new Producer(007, buffer)).start();
		new Thread(new Consumer(123, buffer)).start();
	}
}

//生产者
class Producer implements Runnable {
	int id;
	Buffer buffer;

	public Producer(int id, Buffer buffer) {
		super();
		this.id = id;
		this.buffer = buffer;
	}

	@Override
	public void run() {
		for (int i = 1; i < 10; i++) {
			buffer.set(new Data(i));
			System.out.printf("产出第%d个数据\n", i);
		}
	}
}

//消费者
class Consumer implements Runnable {
	int id;
	Buffer buffer;

	public Consumer(int id, Buffer buffer) {
		super();
		this.id = id;
		this.buffer = buffer;
	}

	@Override
	public void run() {
		for (int i = 1; i < 10; i++) {
			buffer.get();
			System.out.printf("取出第%d个数据\n", i);
		}
	}
}

//缓冲区
class Buffer {
//	默认容量
	Data[] data = new Data[10];
	int count;

//	生产者存入
	public synchronized void set(Data data) {
		while (count == this.data.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.data[count++] = data;
		this.notifyAll();
	}

//	消费者取出
	public synchronized Data get() {
		while (count == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		return this.data[count--];
	}
}

//数据
class Data {
	int id;

	public Data(int id) {
		super();
		this.id = id;
	}
}

参考结果
在这里插入图片描述
信号灯法请见:Java_多线程_并发协作模型_生产者消费者模式_信号灯法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值