Created
March 21, 2013 02:56
-
-
Save abhiramsingh/5210363 to your computer and use it in GitHub Desktop.
The StopLight 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.atomic.AtomicBoolean; | |
import java.util.concurrent.atomic.AtomicLong; | |
/** | |
* This class is thread safe (all methods synchronized) and represents a | |
* StopLight The problem assumes only one StopLight on the pavement hence the | |
* class is made singleton | |
*/ | |
final public class StopLight { | |
private static StopLight sLight; | |
private static LightState state; | |
public static synchronized StopLight getInstance() { | |
if (sLight == null) { | |
sLight = new StopLight(); | |
} | |
return sLight; | |
} | |
private StopLight() { | |
StopLight.state = LightState.GREEN; | |
StopLight.StopWatch.getInstance().start(); | |
} | |
public static synchronized void toggle() { // This method is called by Road | |
// class to toggle the light | |
if (StopLight.state == LightState.RED) { | |
StopLight.state = LightState.GREEN; | |
} else { | |
StopLight.state = LightState.RED; | |
} | |
} | |
public synchronized static LightState getState() { | |
return StopLight.state; | |
} | |
public synchronized static void setState(LightState state) { | |
StopLight.state = state; | |
} | |
static class StopWatch { | |
private static AtomicLong startTime = new AtomicLong(0); | |
private static AtomicLong stopTime = new AtomicLong(0); | |
private static AtomicBoolean running = new AtomicBoolean(false); | |
private static StopWatch sWatch = null; | |
public static synchronized StopWatch getInstance() { | |
if (sWatch == null) { | |
sWatch = new StopWatch(); | |
} | |
return sWatch; | |
} | |
private StopWatch() { | |
} | |
public boolean isRunning() { | |
return running.get(); | |
} | |
public void start() { | |
startTime.set(System.nanoTime()); | |
running.set(true); | |
} | |
public void stop() { | |
stopTime.set(System.nanoTime()); | |
running.set(false); | |
} | |
/* Returns Elapsed time in seconds referencing the point of call*/ | |
public long getElapsedTimeSecs() { | |
long elapsed; | |
if (running.get()) { | |
elapsed = ((System.nanoTime() - startTime.get()) / 1000000000); | |
} else { | |
elapsed = ((stopTime.get() - startTime.get()) / 1000000000); | |
} | |
return elapsed; | |
} | |
public void aSecond() { | |
try { | |
Thread.sleep(Consts.ONE_SEC); | |
} catch (InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment