我正在製作一個多線程應用程序,用戶一次添加1種成分以製作水果沙拉。有最大數量的水果被允許放入碗中。運行多線程的問題
代碼編譯並運行,但問題是它只運行一個線程(Apple)。草莓與蘋果具有相同的睡眠時間(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個蘋果。
- 蘋果最大數量。
這是因爲您無法在單獨的線程中運行這些線程..您在當前線程中運行這兩個線程,這將導致它們按順序執行。 – mre 2013-04-22 23:17:12
我如何在單獨的線程上運行它們? – user2273278 2013-04-22 23:17:56
此外,我會建議有fruitalad參考成分,而不是其他方式。這是標準做法;多對一比一對多要好。 – 2013-04-22 23:18:06