2013-04-22 53 views
0

我正在製作一個多線程應用程序,用戶一次添加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個蘋果。
  • 蘋果最大數量。
+1

這是因爲您無法在單獨的線程中運行這些線程..您在當前線程中運行這兩個線程,這將導致它們按順序執行。 – mre 2013-04-22 23:17:12

+0

我如何在單獨的線程上運行它們? – user2273278 2013-04-22 23:17:56

+0

此外,我會建議有fruitalad參考成分,而不是其他方式。這是標準做法;多對一比一對多要好。 – 2013-04-22 23:18:06

回答

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()。請參閱編輯。

+0

而不是編輯戰鬥,在未來,我建議簡單地回滾你的編輯:) – 2013-04-22 23:22:17

+0

這沒有奏效。它仍然只在運行蘋果 – user2273278 2013-04-22 23:24:37

+0

嗯,是的,因爲它只創建一個蘋果;然後你必須創建一個Strawberry,並以同樣的方式調用'start()'。 – drewmoore 2013-04-22 23:25:35

0

嘗試這樣做,而不是:

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

Thread t2 = new Thread(new Strawberry(ingredient)); 
t2.start(); 
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(); 

你應該叫加入兩個線程在終止前等待它們:

apple.join(); 
strawberry.join(); 
+1

+1用於擴展線程。 – 2013-04-22 23:23:05

+0

是的,擴展線程很棒,除非你需要擴展另一個類。 – drewmoore 2013-04-22 23:30:13