【新手求助】Java多线程(生产者消费者)中的问题,如何终止进程?

Tom Leung 2016-11-18 08:08:09
下面是我的代码,有厨师(生产者)和服务员(消费者)两个任务类,
厨师在桌子上少于五道菜的时候会烧菜,服务业在桌子上有菜的时候会端走菜,
运行挺正常的但是就是不知道为什么停不下来……最后不是调用了exec的shutdown了吗?怎么还是无限运行?
如果改成shutdownNow的话会在sleep那里报错,然后继续无限运行……求解

还有就是代码有哪些错误和写的不好的地方?(第一次写这个肯定有很多…)

package com.imooc;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


class Meal{
private final int id;
Meal(int id){
this.id=id;
}
public String toString(){
return "Meal: "+id;
}
}

class Cook implements Runnable{
private LinkedList<Meal> mealList;
private static int count;
Cook(LinkedList<Meal> mealList){
this.mealList=mealList;
}
public void run(){
while(!Thread.interrupted()){
synchronized(mealList){
while(mealList.size()<5){
System.out.print("厨师正在做这个菜:");
System.out.println(++count);
mealList.add(new Meal(count));
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mealList.notifyAll();
while(mealList.size()==5){
System.out.println("厨师正在等服务员端走菜");
try {
mealList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("厨师下班了");
}
}

class Waiter implements Runnable{
private LinkedList<Meal> mealList;
Waiter(LinkedList<Meal> mealList){
this.mealList=mealList;
}
public void run(){
while(!Thread.interrupted()){
synchronized(mealList){
while(mealList.size()>0){
System.out.println("服务员正在端走这个菜:"+mealList.getLast());
mealList.removeLast();
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mealList.notifyAll();
while(mealList.size()==0){
System.out.println("服务员正在等厨师做菜");
try {
mealList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("服务员下班了");
}
}

public class Manager {

public static void main(String args[]) {
LinkedList<Meal> mealList = new LinkedList<Meal>();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Waiter(mealList));
exec.execute(new Cook(mealList));
exec.execute(new Waiter(mealList));
exec.execute(new Waiter(mealList));
exec.execute(new Cook(mealList));
exec.shutdown();
}

}
...全文
375 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tom Leung 2016-11-18
  • 打赏
  • 举报
回复
运行效果是这样的

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧