运行多个线程的问题

时间:2013-04-22 23:14:46

标签: java multithreading

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

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

Apple.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();
            }
         }
     }
}

Ingredients.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
}

Main.java

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

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

输出:

  • 碗里总共有1个苹果。
  • ....
  • 碗里总共有6个苹果。
  • 最多苹果数。

3 个答案:

答案 0 :(得分:2)

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

您应该将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()。见编辑。

答案 1 :(得分:0)

尝试改为:

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

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

答案 2 :(得分: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();