ユーザーが一度に 1 つの材料を追加してフルーツ サラダを作るマルチスレッド アプリを作成しています。ボウルに入れられる果物の最大数があります。
コードはコンパイルされて実行されますが、問題は 1 つのスレッド (Apple) しか実行されていないことです。Strawberry の thread.sleep(1000) 時間は Apple と同じです。ストロベリーのスリープを別のスリープ時間に変更してみましたが、問題は解決しませんでした。
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();
}
}
}
}
成分.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個のリンゴがあります。
- りんごの最大数。