await/signal/lock实现生产消费者模式

本文深入探讨了使用多线程实现生产者与消费者模式,详细介绍了如何通过并发控制来确保资源的有效分配与管理。通过实例展示了如何利用Java中的并发工具,如Lock、Condition等,实现生产者线程将资源添加到缓冲区,并在消费者线程从缓冲区获取资源时进行同步,从而有效避免了资源竞争和死锁等问题。

存储类GoodStorage:

package main.wll.fish.product;

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

public class GoodStorage {
	private static final int SIZE = 2;
	private List<Good> storage = new ArrayList<Good>(SIZE);

	// 锁
	private final Lock lock = new ReentrantLock();
	// 仓库满的条件变量
	private final Condition full = lock.newCondition();

	// 仓库空的条件变量
	private final Condition empty = lock.newCondition();

	public void add(Good good) {
		lock.lock();
		{
			while (storage.size() >= SIZE) {
				try {
					System.out.println(Thread.currentThread().getName() + "------>product wait.... now ListSIze:"
							+ storage.size());
					full.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			storage.add(good);
			System.out.println(Thread.currentThread().getName() + "------>product :" + good.toString()
					+ ", now ListSIze:" + storage.size());

			empty.signalAll();
		}
		lock.unlock();
	}

	public void remove() {
		lock.lock();
		{
			while (storage.size() == 0) {
				try {
					System.out.println(Thread.currentThread().getName() + "------>consume wait....  now ListSIze:"
							+ storage.size());
					empty.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			Good good = storage.get(0);
			storage.remove(0);
			System.out.println(Thread.currentThread().getName() + "------------------------------------>consume :"
					+ good.toString() + ", now ListSIze:" + storage.size());

			full.signalAll();
			
		}
		lock.unlock();
	}

}

class Good {
	public long id;

	public Good(long id) {
		this.id = id;
	}

	public String toString() {
		return String.format("Good-%d", this.id);
	}
}

生产者:

  1. import java.util.Random;  
  2. import java.util.concurrent.atomic.AtomicInteger;  
  3.   
  4. class Producter implements Runnable {  
  5.     private static AtomicInteger ato = new AtomicInteger(0);  
  6.       
  7.     private GoodStorage store;  
  8.     public Producter(GoodStorage store ){  
  9.         this.store = store;  
  10.     }  
  11.       
  12.       
  13.     public void run() {  
  14.         while(true){  
  15.             try {  
  16.                 Thread.currentThread().sleep(new Random().nextInt(1000));  
  17.                 // queue.put(new Good(System.currentTimeMillis()));  
  18.                 store.add(new Good(ato.incrementAndGet()));  
  19.             } catch (InterruptedException e) {  
  20.                 e.printStackTrace();  
  21.             }  
  22.         }  
  23.     }  
  24. }  

消费者:
  1. import java.util.Random;  
  2.   
  3. class Consumer implements Runnable {  
  4.     private GoodStorage store;  
  5.     public Consumer(GoodStorage store ){  
  6.         this.store = store;  
  7.     }  
  8.       
  9.   
  10.     public void run() {  
  11.         while(true){  
  12.             try {  
  13.                 Thread.currentThread().sleep(new Random().nextInt(1000));  
  14.                 store.remove();  
  15.                   
  16.             } catch (InterruptedException e) {  
  17.                 e.printStackTrace();  
  18.             }  
  19.         }  
  20.     }  
  21. }  

运行主类:
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3.   
  4. public class Main {  
  5.     static ExecutorService pool = Executors.newCachedThreadPool();  
  6.       
  7.     public static void main(String[] args) {  
  8.         GoodStorage store = new GoodStorage();  
  9.         pool.execute(new Producter(store));  
  10.         pool.execute(new Producter(store));  
  11.         pool.execute(new Producter(store));  
  12.           
  13.         pool.execute(new Consumer(store));  
  14.         pool.execute(new Consumer(store));  
  15.     }  
  16. }  

运行结果:

pool-1-thread-8------>product wait.... now ListSIze:2
pool-1-thread-12------>product wait.... now ListSIze:2
pool-1-thread-1------>product wait.... now ListSIze:2
pool-1-thread-7------>product wait.... now ListSIze:2
pool-1-thread-13------>product wait.... now ListSIze:2
pool-1-thread-9------>product wait.... now ListSIze:2
pool-1-thread-17------>product wait.... now ListSIze:2
pool-1-thread-16------>product wait.... now ListSIze:2
pool-1-thread-5------>product wait.... now ListSIze:2
pool-1-thread-20------------------------------------>consume :Good-34532, now ListSIze:1
pool-1-thread-20------------------------------------>consume :Good-34533, now ListSIze:0
pool-1-thread-20------>consume wait....  now ListSIze:0
pool-1-thread-21------>consume wait....  now ListSIze:0
pool-1-thread-6------>product :Good-34534, now ListSIze:1
pool-1-thread-6------>product :Good-34535, now ListSIze:2
pool-1-thread-6------>product wait.... now ListSIze:2
pool-1-thread-10------>product wait.... now ListSIze:2
pool-1-thread-2------>product wait.... now ListSIze:2
pool-1-thread-14------>product wait.... now ListSIze:2
pool-1-thread-18------>product wait.... now ListSIze:2
pool-1-thread-3------>product wait.... now ListSIze:2
pool-1-thread-11------>product wait.... now ListSIze:2
pool-1-thread-15------>product wait.... now ListSIze:2
pool-1-thread-19------>product wait.... now ListSIze:2
pool-1-thread-4------>product wait.... now ListSIze:2
pool-1-thread-8------>product wait.... now ListSIze:2
pool-1-thread-12------>product wait.... now ListSIze:2
pool-1-thread-1------>product wait.... now ListSIze:2
pool-1-thread-7------>product wait.... now ListSIze:2
pool-1-thread-13------>product wait.... now ListSIze:2
pool-1-thread-9------>product wait.... now ListSIze:2
pool-1-thread-17------>product wait.... now ListSIze:2
pool-1-thread-16------>product wait.... now ListSIze:2
pool-1-thread-5------>product wait.... now ListSIze:2
pool-1-thread-20------------------------------------>consume :Good-34534, now ListSIze:1
pool-1-thread-20------------------------------------>consume :Good-34535, now ListSIze:0
pool-1-thread-20------>consume wait....  now ListSIze:0
pool-1-thread-21------>consume wait....  now ListSIze:0







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值