简体   繁体   English

Java:多线程

[英]Java: Multi Threading

/* Whats went wrong here, every time producer only executing and consumer not consuming anything. / *这里出了什么问题,每次生产者只执行而消费者不消费任何东西。 Please explain me what went wrong in this code. 请向我解释这段代码出了什么问题。

My Expected Result : Producer Produce 1 item then Consumer has to consume that item */ 我的预期结果:生产者生产1个项目,然后消费者必须消耗该项目* /

import java.util.ArrayList;

public class ConsumerAndProducerMain
{
    public static void main(String[] args) throws InterruptedException
    {
        int MAX_SIZE = 10;
        ArrayList<Integer> list = new ArrayList<Integer>(10);
        final Producer producer = new Producer(MAX_SIZE, list);
        final Consumer consumer = new Consumer(MAX_SIZE, list);
        Thread t1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    producer.producer();
                }
                catch (InterruptedException e)
                {
                    System.out.println("Producer : Exception occured because of multi threading...");
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    consumer.consumer();
                }
                catch (InterruptedException e)
                {
                    System.out.println("Consumer : Exception occured because of multi threading...");
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Program terminated..");
    }
}

class Producer {
    int size;
    ArrayList<Integer> list;
    public Producer(int size, ArrayList<Integer> list)
    {
        this.size = size;
        this.list = list;
    }
    public void producer() throws InterruptedException{
        int value = 0;
        while(true){
            synchronized (this)
            {
                if(list.size() == size){
                    System.out.println("Producer : List is full");
                    wait();
                }else{
                    list.add(++value);
                    Thread.sleep(200);
                    notify();
                    System.out.println("Value produce by the producer : "+value);
                }
            }
        }
    }
}

class Consumer {
    int size;
    ArrayList<Integer> list;
    public Consumer(int size, ArrayList<Integer> list)
    {
        this.size = size;
        this.list = list;
    }
    public void consumer() throws InterruptedException{
        while(true){
            synchronized (this)
            {
                if(list.isEmpty()){
                    System.out.println("Consumer : List is empty");
                    wait();
                }else{
                    int removedItem = list.remove(list.size());
                    Thread.sleep(5000);
                    notify();
                    System.out.println("Value consumed by the consumer : "+removedItem);
                }
            }
        }
    }
}

First of all you need to sycnhronize, wait and notify for the list you use, not for objects Producer and Consumer you do. 首先,您需要同步,等待并通知您使用的列表,而不是您要使用的Producer和Consumer对象。

Producer: 制片人:

final ArrayList<Integer> list;
// ...
synchronized (list) {
  if (list.size() == size) {
    System.out.println("Producer : List is full");
    list.wait();
  } else {
    list.add(++value);
    Thread.sleep(200);
    list.notify();
    System.out.println("Value produce by the producer : " + value);
  }
}

Consumer: 消费者:

final ArrayList<Integer> list;
// ...
synchronized (list) {
  if (list.isEmpty()) {
    System.out.println("Consumer : List is empty");
    list.wait();
  } else {
    int removedItem = list.remove(list.size() - 1);
    Thread.sleep(200);
    list.notify();
    System.out.println("Value consumed by the consumer : " + removedItem);
  }
}

The output is look like: 输出如下所示:

Value produce by the producer : 1
Value produce by the producer : 2
Value produce by the producer : 3
Value produce by the producer : 4
Value produce by the producer : 5
Value produce by the producer : 6
Value produce by the producer : 7
Value produce by the producer : 8
Value produce by the producer : 9
Value produce by the producer : 10
Producer : List is full
Value consumed by the consumer : 10
Value consumed by the consumer : 9
Value consumed by the consumer : 8
...

For your expected result (Producer produce 1 item then Consumer has to consume that item) you need to change logic with order of wait and notify: Producer add item, notify, then wait for Consumer notify, Consumer wait for Producer notify, consume 1 item then wait for Producer notify again. 对于您的预期结果(生产者生产1个项目,然后消费者必须消耗该项目),您需要按等待顺序更改逻辑并通知:生产者添加项目,进行通知,然后等待消费者通知,消费者等待生产者通知,消耗1个项目然后等待生产者再次通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM