Reputation: 695
I am trying to use multithreading in java by having 2 threads, one of the threads represents a car travelling one way through an intersection, the other represents another car waiting to travel through the intersection. My problem is that car2 prints out "car2 is waiting to cross" more times than it should(it should only print it 6 times). I have tried using syncronization but that doesnt work. Its a pretty simple programme that im trying to make to help myself understand multithreading, its shown below.
public class Drive {
public static Thread car1;
public static Thread car2;
public static void main(String[]args){
Cars cars = new Cars();
car1 = new Thread(cars, "car 1");
car2 = new Thread(cars, "car 2");
car1.start();
car2.start();
}
}
public class Cars implements Runnable{
int distance = 0;
public void increaseDistance(){
distance ++;
}
public void race(){
while(distance <= 5){
if(Thread.currentThread().getName().equals("car 1")){
System.out.println("Distance covered by " + Thread.currentThread().getName() + " is " + distance + " meters");
increaseDistance();
}
if(Thread.currentThread().getName().equals("car 2")){
System.out.println(Thread.currentThread().getName() + " is waiting to cross");
}
}
}
public void run(){
race();
}
}
Output im getting below...
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
Distance covered by car 1 is 0 meters
car 2 is waiting to cross
Distance covered by car 1 is 1 meters
Distance covered by car 1 is 2 meters
Distance covered by car 1 is 3 meters
Distance covered by car 1 is 4 meters
Distance covered by car 1 is 5 meters
car 2 is waiting to cross
Where it says "car 2 is waiting to cross" that should be printing out the same amount of times as "Distance covered by car 1 is x meters", but its random every time?
Upvotes: 2
Views: 792
Reputation: 4241
It is not necessary for the race() method of car2 to execute only once after incrementDistance() method of car1 has been called. It is possible for this method to be called multiple times. Welcome to the irregular world of scheduling.
What you should be doing is to use conditions to notify car2 that car1 has called incrementDistance() and car2 should wait on this condition in its race() method. That will ensure that car2 prints the expected output..
Upvotes: 2
Reputation: 11433
Thread "car 1" is the only one that increments the distance and determines when the loop stops. Since threads run independently and at varying speeds, the number of times "car 2" prints will be unpredictable.
Upvotes: 0