有两个线程在main()中  分别是cooker和waiter我希望在cooker中的count到达10的时候 让线程停下来 请问我应该在下面的**************************************加入什么代码  谢谢import java.util.concurrent.*;
public class Restaurant_No001 { /**
 * @param args
 */
Meal meal;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Restaurant_No001 YY = new Restaurant_No001();
ExecutorService exec =Executors.newCachedThreadPool();
exec.execute(new Cooker(YY));
exec.execute(new Waiter(YY));
//Thread thread1 = new Thread(new Cooker(YY));
//Thread thread2 = new Thread(new Waiter(YY));
//thread1.start();
//thread2.start();


}}class Waiter implements Runnable{
Restaurant_No001 restaurant;
public Waiter (Restaurant_No001 restaurant){
this.restaurant = restaurant;
}
public void run(){
while(!Thread.interrupted()){
synchronized ("cw"){
while (restaurant.meal == null){
try{"cw".wait();}catch (InterruptedException  e){}
}
System.out.println("No " + restaurant.meal.meal_number + " is eating");
restaurant.meal = null;
}
synchronized ("wc"){
"wc".notify();
}
}
}
}class Cooker implements Runnable{
Restaurant_No001 restaurant;
private static int count = 1;
public Cooker (Restaurant_No001 restaurant){
this.restaurant = restaurant;
}
public void run(){
while(!Thread.interrupted()){
 while (restaurant.meal != null){
synchronized("wc"){try{"wc".wait();}catch (InterruptedException  e){}}
}
if(count >= 10){
System.out.println("the restaurant is full of people");
//*****************************************
}
synchronized ("cw"){
if (restaurant.meal == null){
restaurant.meal = new Meal(++count);
System.out.println("cooker is cooking meal No " + restaurant.meal.meal_number);
"cw".notify();
}
}
}
}
}class CleanBoy implements Runnable{
public void run(){}
}class Meal{

protected final int meal_number;
public Meal(int number){
this.meal_number = number;
}
}

解决方案 »

  1.   

    可以用自己的方法来控制,结束run方法就可以了,或者调用线程的stop方法,但是这个方法很不安,优势会造成资源浪费或者死循环,所以被取消了,或者过失了,都是用自己的方式来控制线程技术的,就像结束循环一样.
      

  2.   


    我是想在cooker中的count来做计数器 当他到10的时候就停止运行 请问应该如何?
      

  3.   

    http://software.ccidnet.com/art/322/20030410/43222_1.html
    这个应该有帮助~
      

  4.   

    你的程序有点问题,不要用
    在类中声明个staitc String lock =cw;
    synchronized ("cw")
    synchronized (lock)
    因为字符串常量池的原因你的代码才不会出错但不证明是对的。
      

  5.   

    另外你是让他停止还是让他暂停性质是不一样的。
    停止的话break就行了,暂停的话因为你的代码错误比较多,不好修改。
    生产者消费者问题请见
    http://blog.csdn.net/sunyujia/category/371789.aspx