我正在制作一个多线程应用程序,用户一次添加一种成分来制作水果沙拉。允许将最大数量的水果放入碗中。
代码编译并运行,但问题是它只运行一个线程(Apple)。Strawberry 的 thread.sleep(1000) 时间与苹果相同。我尝试将草莓的睡眠更改为不同的睡眠时间,但并没有解决问题。
苹果.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
}
主.java
public class Main
{
public static void main( String[] args )
{
Ingredients ingredient = new FruitSalad();
new Apple(ingredient).run();
new Strawberry(ingredient).run();
}
}
输出:
- 碗里总共有 1 个苹果。
- ……
- 碗里总共有 6 个苹果。
- 苹果的最大数量。