java multithreading : traffic intersection system -


i trying use multithreading in java having 2 threads, 1 of threads represents car travelling 1 way through intersection, other represents car waiting travel through intersection. problem car2 prints out "car2 waiting cross" more times should(it should print 6 times). have tried using syncronization doesnt work. pretty simple programme im trying make myself understand multithreading, 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 " + thread.currentthread().getname() + " " + distance + " meters");                 increasedistance();              }              if(thread.currentthread().getname().equals("car 2")){                  system.out.println(thread.currentthread().getname() + " waiting cross");             }          }      }         public void run(){         race();     } } 

output im getting below...

car 2 waiting cross car 2 waiting cross car 2 waiting cross car 2 waiting cross car 2 waiting cross distance covered car 1 0 meters car 2 waiting cross distance covered car 1 1 meters distance covered car 1 2 meters distance covered car 1 3 meters distance covered car 1 4 meters distance covered car 1 5 meters car 2 waiting cross 

where says "car 2 waiting cross" should printing out same amount of times "distance covered car 1 x meters", random every time?

it not necessary race() method of car2 execute once after incrementdistance() method of car1 has been called. possible method called multiple times. welcome irregular world of scheduling.

what should doing use conditions notify car2 car1 has called incrementdistance() , car2 should wait on condition in race() method. ensure car2 prints expected output..


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -