java 使用信号量Semaphore实现生产者-消费者模式
2023-09-20 10:52:00 #笔记 #后端开发 #面试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class Cache { private int cacheSize = 0; public Semaphore mutex; public Semaphore empty; public Semaphore full; public Cache(int size) { mutex = new Semaphore(1); empty = new Semaphore(size); full = new Semaphore(0); } public int getCacheSize()throws InterruptedException{ return cacheSize; } public void produce() throws InterruptedException{ empty.acquire(); mutex.acquire(); cacheSize++; System.out.println("生产了一个产品, 当前产品数为" + cacheSize); mutex.release(); full.release(); } public void consume() throws InterruptedException{ full.acquire(); mutex.acquire(); cacheSize--; System.out.println("消费了一个产品, 当前产品数为" + cacheSize); mutex.release(); empty.release(); } }
|