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();
        }
    }

  • 相关阅读:
    python3.5: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory
    php回溯
    PHPredis长连接pconnect
    php操作redis出现不报错就退出
    MSMQ消息队列
    消息队列使用的四种场景介绍(准载)
    Spring MVC参数封装传递
    Spring MVC配置实例
    .NET项目中使用PostSharp
    C#进阶系列——AOP
  • 原文地址:https://www.cnblogs.com/javaitpx/p/2769333.html
Copyright © 2011-2022 走看看