簡體   English   中英

運行多個線程的問題

[英]Problems with running multiple threads

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

當您在另一個線程中直接調用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() 見編輯。

嘗試這樣做:

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

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

讓你的類擴展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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM