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

  • 相关阅读:
    动画处理<并行和串行>
    flutter 动画 practice
    flutter AnimationBuilder
    flutter 动画
    Flutter Animation AnimatedBuilder
    Flutter 与 Android 的交互
    Flutter:教你用CustomPaint画一个自定义的CircleProgressBar
    Flutter裁剪图片
    Flutter 实现图片裁剪
    soundpool
  • 原文地址:https://www.cnblogs.com/javaitpx/p/2769333.html
Copyright © 2011-2022 走看看