0

我正在制作一个多线程应用程序,用户一次添加一种成分来制作水果沙拉。允许将最大数量的水果放入碗中。

代码编译并运行,但问题是它只运行一个线程(Apple)。Strawberry 的 thread.sleep(1000) 时间与苹果相同。我尝试将草莓的睡眠更改为不同的睡眠时间,但并没有解决问题。

苹果.java

public class Apple implements Runnable
{
    private Ingredients ingredient;

    public Apple(Ingredients ingredient)
    {   
        this.ingredient = ingredient;
    }

    public void run() 
    {
        while(true)
        {
            try 
            { 
                Thread.sleep(1000);
                ingredient.setApple(6);
            } 
            catch (InterruptedException e) 
            { 
                e.printStackTrace();
            }
         }
     }
}

配料.java

public interface Ingredients 
{
    public void setApple(int max) throws InterruptedException;
    public void setStrawberry(int max) throws InterruptedException;
}

FruitSalad.java

public class FruitSalad implements Ingredients
{
    private int apple = 0;
    private int strawberry = 0;

    public synchronized void setApple(int max) throws InterruptedException 
    {
        if(apple == max)
            System.out.println("Max number of apples.");
        else
        {
            apple++;
            System.out.println("There is a total of " + apple + " in the bowl.");
        }
    }
    //strawberry
}

主.java

public class Main 
{
       public static void main( String[] args )
       {
           Ingredients ingredient = new FruitSalad();

           new Apple(ingredient).run();
           new Strawberry(ingredient).run();   
       }
}

输出:

  • 碗里总共有 1 个苹果。
  • ……
  • 碗里总共有 6 个苹果。
  • 苹果的最大数量。
4

3 回答 3

2

当您.run()直接在另一个线程中调用 Runnable 上的方法时,您只需将该“线程”添加到同一个堆栈(即它作为单个线程运行)。

您应该将 Runnable 包装在一个新线程中并用于.start()执行该线程。

Apple apple = new Apple(ingredient);
Thread t = new Thread(apple);
t.start();


Strawberry strawberry = new Strawberry(ingredient);   
Thread t2 = new Thread(strawberry);
t2.start();

您仍然直接调用 run() 方法。相反,您必须调用该start()方法,该方法run()在新线程中间接调用。见编辑。

于 2013-04-22T23:18:40.477 回答
0

尝试这样做:

Thread t1 = new Thread(new Apple(ingredient));
t1.start;

Thread t2 = new Thread(new Strawberry(ingredient));
t2.start();
于 2013-04-22T23:19:27.770 回答
0

让你的课程扩展Thread

public class Apple extends Thread
public class Strawberry extends Thread

然后你可以启动这些线程:

Apple apple = new Apple(ingredient);
Strawberry strawberry = new Strawberry(ingredient);   

apple.start();
strawberry.start();

您应该在两个线程上调用 join 以在终止之前等待它们:

apple.join();
strawberry.join();
于 2013-04-22T23:22:34.883 回答