簡體   English   中英

Java Threads生產者消費者計划

[英]Java Threads producer consumer program

我正在嘗試用Java編寫生產者消費者程序,生產者在隊列中插入3個數字,消費者從隊列中刪除這些數字。 我已根據自己的Linkedlist實現實現了自己的Queue。

當我運行我的代碼時,我的生產者終止,但我的消費者永遠不會終止。 我無法弄清楚原因

public class ProdConMain {

public static void main(String[] args) throws InterruptedException {

    MyQueue queue = new MyQueue();
    queue.setLimit(3);
    Thread producer = new Thread(new Producer(queue));
    Thread consumer = new Thread(new Consumer(queue));

    producer.start();
    consumer.start();


    try {
        producer.join();
        System.out.println("Producer: " + producer.getState());
        consumer.join();

        System.out.println("Consumer: " + consumer.getState());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(queue.list.toString());

}


}



public class Producer implements Runnable {

MyQueue queue = new MyQueue();
Random random = new Random();
public Producer(MyQueue queue) {
    this.queue = queue;
}

@Override
public void run() {
    int i = 1;
    while (i < 10) {

        synchronized (queue) {
            if (queue.getSize() < queue.getLimit()) {
                int value = random.nextInt(500);
                queue.enqueue(value);
                System.out.println("Inserted: " + value);
                queue.notify();
            } else {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        i++;
    }
  }
}


public class Consumer implements Runnable {

  MyQueue queue = new MyQueue();

  public Consumer(MyQueue queue) {
    this.queue = queue;
}

  @Override
  public void run() {

     while (true) {
        synchronized (queue) {

            if (queue.isEmpty()) {
                {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                int value = queue.dequeue();
                System.out.println("Removed:        " + value);
                queue.notify();
            }
        }
    }
  }
}

您需要在消費者的while(true)循環中添加一個停止條件,否則它將永遠不會完成。 您可以在while條件下執行此操作:

while(shouldConsume()) { 
    // consume ...
}

或者,如果達到條件,則打破無限循環:

while(true) { 
    // consume ...

    if (shouldStopConsume()) {
        break;
    }
}

然后你只需要使用適合你的用例的停止條件來實現這些方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM