Created
March 21, 2013 02:54
-
-
Save abhiramsingh/5210356 to your computer and use it in GitHub Desktop.
The Car Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test.concurrency.traffic; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class Car implements Callable<Car> { | |
private static StopLight sLight = StopLight.getInstance(); // StopLight will | |
// be injected | |
// into Car | |
private AtomicInteger pos; // Position of car before stop light | |
final private String name; | |
public String getName() { | |
return name; | |
} | |
public Car(AtomicInteger pos, String name) throws IllegalArgumentException { | |
super(); | |
if (pos.get() < 0 || pos.get() > Consts.PAVEMENT_LENGTH) { | |
throw new IllegalArgumentException("Argument value not in range..."); | |
} | |
this.name = name; | |
this.pos = pos; | |
} | |
private void goAhead() { // Move car ahead on road by one unit | |
try { | |
Thread.sleep(Consts.ONE_SEC); // one unit per second | |
pos.addAndGet(1); | |
} catch (InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
public synchronized AtomicInteger getPos() { | |
return pos; | |
} | |
@Override | |
public Car call() { | |
if (pos.get() > Consts.PAVEMENT_LENGTH / 2) { // Once car crosses the | |
// StopLight, simply move it ahead till end of the Road | |
while (getPos().get() != Consts.PAVEMENT_LENGTH) { | |
goAhead(); | |
} | |
} else { | |
while (pos.get() != Consts.PAVEMENT_LENGTH) { | |
synchronized (sLight) { // StopLight instance used as Object | |
// monitor to make cars wait on signal until | |
// notified by Road | |
while (StopLight.getState() == LightState.RED | |
&& pos.get() == Consts.PAVEMENT_LENGTH / 2) { | |
try { | |
sLight.wait(10 * Consts.ONE_SEC); // wait until Road | |
// toggles | |
// stoplight and | |
// invokes | |
// notify | |
} catch (InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} | |
goAhead(); // Move car one unit ahead | |
} | |
} | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment