其实应该说是 模拟 多线程对一个数组同时进行读取的功能(缓冲区)
变量 count 表示缓冲区剩余数据的个数 为0时则要求读进程等待,等于数组长度时,则要求写进程等待
这样能避免对同一个数据重复取,或者覆盖写- package demo;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class ProducerAndConsumerByBuffer {
- /**
- * 利用数组解决生产消费问题
- */
- public static void main(String[] args) {
- final Buff b = new Buff();
- new Thread(){
- public void run() {
- while(true)
- b.pro();
- };
- }.start();
- new Thread(){
- public void run() {
- while(true)
- b.con();
- };
- }.start();
- new Thread(){
- public void run() {
- while(true)
- b.pro();
- };
- }.start();
- }
- }
- class Buff{
- private int[] buf = new int[5];
- private int proPos = 0,conPos=0;//数组指针
- private int count = 0;//指示剩余数量
- Lock lock = new ReentrantLock();
- Condition notFull = lock.newCondition();
- Condition notEmpty = lock.newCondition();
- public void pro(){
- lock.lock();
- try{
- while(count==buf.length){ //缓冲区已满 待取走
- try {
- notEmpty.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- buf[proPos] = 1;
- System.out.println(Thread.currentThread().getName()+"...生产"+proPos);
- if((++proPos)==buf.length)
- proPos = 0;
- count++;
- notFull.signal();
- }finally{
- lock.unlock();
- }
- }
- public void con(){
- lock.lock();
- try{
- while(count==0){ //缓冲区已空 待新数据
- try {
- notFull.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- buf[conPos] = 0;
- System.out.println(Thread.currentThread().getName()+"...消费"+conPos);
- if(++conPos == buf.length)
- conPos = 0;
- count--;
- notEmpty.signal();
- }finally{
- lock.unlock();
- }
- }
- }
复制代码
|
|