Reputation: 1315
Im making an multithread app where the user adds in 1 ingredient at a time to make a fruit salad. There is a max number of fruits allowed to be put into the bowl.
The code compiles and run, but the problem is that it is only running one thread (Apple). Strawberry has the same thread.sleep(1000) time as apple. I have tried changing strawberry's sleep to a different sleep time but it did not fix the problem.
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();
}
}
Output:
Upvotes: 0
Views: 880
Reputation: 32690
When you call the .run()
method on a Runnable directly within another thread, you simply add that "thread" to the same stack (i.e. it runs as a single thread).
You should instead wrap the Runnable in a new thread and use .start()
to execute the thread.
Apple apple = new Apple(ingredient);
Thread t = new Thread(apple);
t.start();
Strawberry strawberry = new Strawberry(ingredient);
Thread t2 = new Thread(strawberry);
t2.start();
You're still calling the run() method directly. Instead, you have to call the start()
method, which calls run()
indirectly in a new thread. See edit.
Upvotes: 2
Reputation: 14842
Have your classes extend Thread
:
public class Apple extends Thread
public class Strawberry extends Thread
Then you can start those threads:
Apple apple = new Apple(ingredient);
Strawberry strawberry = new Strawberry(ingredient);
apple.start();
strawberry.start();
You should call join on both threads to wait for them before terminating:
apple.join();
strawberry.join();
Upvotes: 0
Reputation: 11117
Try doing that instead:
Thread t1 = new Thread(new Apple(ingredient));
t1.start;
Thread t2 = new Thread(new Strawberry(ingredient));
t2.start();
Upvotes: 0