2016-08-07 97 views
1

我想写一个生产者消费者程序在Java中生产者在队列中插入3个数字和消费者从队列中删除这些数字。我已经根据自己的Linkedlist实现实现了自己的队列。Java线程生产者消费者程序

当我运行我的代码时,我的生产者终止,但我的消费者永远不会终止。我无法弄清楚为什么

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

'消费者'永远不会终止,因为你正在使用无限循环'while(true)' –

回答

0

你需要一个停止条件添加到而(真)在消费者循环,否则将永远不会结束。您可以在条件本身做到这一点:

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

或打破无限循环如果达到条件:

while(true) { 
    // consume ... 

    if (shouldStopConsume()) { 
     break; 
    } 
} 

然后你只需要实现与停止那些方法适合您的用例的条件。

+0

我明白了,谢谢。现在它适用于我。 队列类 - public volatile boolean doneProcessing; (实例变量) 生产者类 - queue.doneProcessing = true; (从while循环退出后) 使用者类 - while(!queue.doneProcessing) – Jehan