消费者-生产者多种实现方式

package com.zz.producerandconsumer;

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

/**
 * @author Zhang Zhen
 * @time 2019年4月6日 下午11:41:20
 */

/*
 * topic——消费者和生产者
 * 1.多个消费者、多个生产者
 * 2.长度固定的缓冲区、先生产的先被消费
 * 3.满不生产、空不消费
 * 4.生产者*每个生产者生产次数 = 消费者*每个消费者消费次数
 * 
 * 将采用Lock、Synchronized以及Semaphores三种方式实现
 * 对于BlockingQueue,它仅仅满足了上述条件中的3,对于统计其它信息(如id,num……),依旧是非线程安全的(声明为volatile也不行,复合操作++,无法保证原子性);
 * 对于PipedInputSteam和PipedOutputStream,不满足条件1;
 */

public class Bylock {

	private static Integer num = 1;
	private static final int MAX = 5;
	private static int id = 0;

	public static void main(String[] args) {

		LinkedList<Integer> buffer = new LinkedList<>();

		Lock mutex = new ReentrantLock();
		Condition isFull = mutex.newCondition();
		Condition isEmpty = mutex.newCondition();

		int cnt = 0;
		while (cnt++ < 4) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int x = 1; x <= 3; x++) {
						mutex.lock();
						try {
							while (buffer.size() == MAX) {
								isFull.await();
							}
							buffer.offer(num);
							System.out.println("id = " + (++id) + " Producer-" + Thread.currentThread().getId()
									+ " produde " + (num++) + " " + x + "th.");
							System.out.println("the buffer: " + buffer);
							isEmpty.signalAll();
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
							mutex.unlock();
						}
						try {
							TimeUnit.SECONDS.sleep(1);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}

		int cnt1 = 0;
		while (cnt1++ < 3) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int x = 1; x <= 4; x++) {
						mutex.lock();
						try {
							while (buffer.isEmpty()) {
								isEmpty.await();
							}
							System.out.println("id = " + (++id) + " Consumer-" + Thread.currentThread().getId()
									+ " consume " + buffer.peek() + " " + x + "th.");
							buffer.poll();
							System.out.println("the buffer: " + buffer);
							isFull.signalAll();
						} catch (Exception e) {
						} finally {
							mutex.unlock();
						}
						try {
							TimeUnit.SECONDS.sleep(1);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
	}

}

package com.zz.producerandconsumer;

import java.util.LinkedList;

/**
 * @author Zhang Zhen
 * @time 2019年4月7日 下午1:57:35
 */

public class BySynchronized {

	private static final int MAXSISE = 5;
	private static LinkedList<Integer> buffer = new LinkedList<>();
	private static int id = 1;
	private static int num = 1;

	private static Object mutex = new Object();

	public static void main(String[] args) {
		int cnt = 0;
		while (cnt++ < 4) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int i = 1; i <= 3; i++) {
						synchronized (mutex) {
							while (buffer.size() == MAXSISE) {
								try {
									mutex.wait();
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}

							buffer.offer(num);
							System.out.printf("ID=%02d", id);
							System.out.print(" P=" + Thread.currentThread().getId());
							System.out.printf(" p:%02d", num);
							System.out.printf(" " + i + "th");
							System.out.println(" buffer:" + buffer);
							num++;
							id++;

							mutex.notifyAll();
						}
					}
				}
			}).start();
		}

		int cnt1 = 0;
		while (cnt1++ < 3) {
			new Thread(new Runnable() {

				@Override
				public void run() {

					for (int i = 1; i <= 4; i++) {
						synchronized (mutex) {
							while (buffer.isEmpty()) {
								try {
									mutex.wait();
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}

							System.out.printf("ID=%02d", id);
							System.out.print(" C=" + Thread.currentThread().getId());
							System.out.printf(" c:%02d", buffer.peek());
							System.out.printf(" " + i + "th");
							buffer.poll();
							System.out.println(" buffer:" + buffer);
							id++;

							mutex.notifyAll();
						}
					}
				}
			}).start();
		}
	}

}

package com.zz.producerandconsumer;

import java.util.LinkedList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Zhang Zhen
 * @time 2019年4月7日 下午2:56:32
 */
public class BySemaphore {

	private static final int MAXSIZE = 8;
	private static int id = 1;
	private static int num = 1;
	private static LinkedList<Integer> buffer = new LinkedList<>();

	private static Semaphore mutex = new Semaphore(1);
	private static Semaphore full = new Semaphore(0);
	private static Semaphore empty = new Semaphore(MAXSIZE);

	public static void main(String[] args) {
		int cnt = 0;
		while (cnt++ < 3) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int i = 1; i <= 4; i++) {
						try {
							full.acquire();
							mutex.acquire();
							System.out.printf("ID=%02d", id);
							System.out.print(" C=" + Thread.currentThread().getId());
							System.out.printf(" c:%02d", buffer.peek());
							System.out.printf(" " + i + "th");
							buffer.poll();
							System.out.println(" buffer:" + buffer);
							id++;

						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
							mutex.release();
							empty.release();
						}
						try {
							TimeUnit.SECONDS.sleep(1);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
		int cnt1 = 0;
		while (cnt1++ < 4) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int i = 1; i <= 3; i++) {
						try {
							empty.acquire();
							mutex.acquire();
							buffer.offer(num);
							System.out.printf("ID=%02d", id);
							System.out.print(" P=" + Thread.currentThread().getId());
							System.out.printf(" p:%02d", num);
							System.out.printf(" " + i + "th");
							System.out.println(" buffer:" + buffer);
							num++;
							id++;
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
							mutex.release();
							full.release();
						}
						try {
							TimeUnit.SECONDS.sleep(1);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}

	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值