zoukankan      html  css  js  c++  java
  • 用JAVA中的多线程示例生产者和消费者问题

    package com.softeem.demo;

    class Producer implements Runnable {
        private SyncStack stack;

        public Producer(SyncStack stack) {
            this.stack = stack;
        }

        public void run() {
            for (int i = 0; i < stack.getProducts().length; i++) {
                String product = "产品" + i;
                stack.push(product);
                System.out.println("生产了: " + product);
                try {
                    Thread.sleep(200);
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class Consumer implements Runnable {
        private SyncStack stack;

        public Consumer(SyncStack stack) {
            this.stack = stack;
        }

        public void run() {
            for (int i = 0; i < stack.getProducts().length; i++) {
                String product = stack.pop();
                System.out.println("消费了: " + product);
                try {
                    Thread.sleep(1000);
                catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }

    class SyncStack {
        private String[] products = new String[10];
        private int index;

        public synchronized void push(String product) {
            if (index == product.length()) {
                try {
                    wait();
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            notify();
            products[index= product;
            index++;
        }

        public synchronized String pop() {
            if (index == 0) {
                try {
                    wait();
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            notify();
            index--;
            String product = products[index];
            return product;
        }

        public String[] getProducts() {
            return products;
        }

    }

    public class TestProducerConsumer {

        public static void main(String[] args) {
            SyncStack stack = new SyncStack();
            Producer p = new Producer(stack);
            Consumer c = new Consumer(stack);

            new Thread(p).start();
            new Thread(c).start();
        }
    }

  • 相关阅读:
    python之路——进程
    python之路——操作系统的发展史
    python之路——网络编程
    模块学习之re模块
    day11迭代器、生成器
    day10闭包、函数装饰器
    vnc安装和配置
    单例模式
    代理设计模式
    工厂模式例子
  • 原文地址:https://www.cnblogs.com/javaitpx/p/2769333.html
Copyright © 2011-2022 走看看