Reputation: 2938
I am trying to implement traffic signal in java using multi threading concepts. I want to use synchronization. This is code i have written but it doesn't run according to my expectations :P .. What i am actually doing is taking a variable "a" whose value determines which light should be on at a particular time. For eg: a==0 should give red light.. then red light acquires a lock on "a" and changes the value to a==1 after some interval and then switches on to orange light and the same happens for green light as well ..
Code:
package test;
class Lights implements Runnable {
int a=0,i,j=25;
synchronized public void valueA()
{
a=a+1;
}
public void showLight()
{
System.out.println("The Light is "+ Thread.currentThread().getName());
}
@Override
public void run() {
// TODO Auto-generated method stub
for(i=25;i>=0;i--)
{
while(j<=i&&j>=10&&a==0)
{
showLight();
/*some code here that locks the value of "a" for thread 1
and keeps it until thread 1 unlocks it! */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
j--;
}
while(j<10&&j>=5&&a==1)
{
showLight();
/*some code here that locks the value of "a" for thread 1
and keeps it until thread 1 unlocks it! */
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
j--;
}
while(j<5&&j>=0&&a==2)
{
showLight();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Main Class:
package test;
public class MainTraffic {
public static void main(String args[])
{
Runnable lights=new Lights();
Thread one=new Thread(lights);
Thread two=new Thread(lights);
Thread three=new Thread(lights);
one.setName("red");
two.setName("orange");
three.setName("green");
one.start();
two.start();
three.start();
}
}
Upvotes: 2
Views: 11571
Reputation: 26185
synchronized(this) is not very useful when you have several different instances of the class. Only block that are synchronized on the same object are prevented from running in parallel.
One option would be to pass a common object, perhaps containing the "a" you want them to use, to the Lights constructor and have the threads synchronize on that object.
Upvotes: 1