我正在制作一个多线程应用程序,用户一次添加一种成分来制作水果沙拉。碗中可放入的水果数量有上限。
代码编译并运行,但问题是它只运行一个线程(Apple)。草莓的 thread.sleep(1000) 时间与苹果相同。我尝试过将草莓的 sleep 时间更改为不同的 sleep 时间,但没有解决问题。
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 个苹果。
- 苹果的最大数量。
最佳答案
当您直接在另一个线程中调用 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()
。请参阅编辑。
关于java - 运行多线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16158292/