生产者-消费者问题

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

public class ProductConsume {
    static WareHouse buffer = new WareHouse();

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            Thread thread1 = new Thread(new Producer());
            thread1.setName(String.format("Producer%d", i));
            thread1.start();
            Thread thread2 = new Thread(new Consumer());
            thread2.setName(String.format("Consumed%d", i));
            thread2.start();
        }
    }

    static class WareHouse {
        final Semaphore Full = new Semaphore(0);
        final Semaphore Empty = new Semaphore(10);
        final Semaphore mutex = new Semaphore(1);
        Queue<Object> items = new LinkedList<>();
        public void put(Object item) throws InterruptedException {
            Empty.acquire();
            mutex.acquire();
            try {
                items.add(item);
                System.out.printf("%s, in : %d, remain: %d\n", Thread.currentThread().getName(), item, buffer.items.size());
            } finally {
                mutex.release();
                Full.release();
            }
        }
        public void take() throws InterruptedException {
            Full.acquire();
            mutex.acquire();
            try {
                Object item = items.poll();
                System.out.printf("%s, out: %d, remain: %d\n", Thread.currentThread().getName(), item, buffer.items.size());
            } finally {
                mutex.release();
                Empty.release();
            }
        }
    }

    static class Producer implements Runnable {
        static int item;
        @Override
        public void run() {
            while (true) {
                int n = item++;
                try {
                    buffer.put(n);
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    buffer.take();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容