Created
February 6, 2013 16:58
-
-
Save karthikmit/4723996 to your computer and use it in GitHub Desktop.
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
public class SynchronizationTests { | |
@Test | |
public void testMultipleIncrementers() throws InterruptedException { | |
SimpleLongCounter counter = new SimpleLongCounter(); | |
List<SimpleIncrementer> simpleIncrementerList = new ArrayList<SimpleIncrementer>(); | |
for(int i = 0; i < 3; i++) { | |
simpleIncrementerList.add(new SimpleIncrementer(counter)); | |
} | |
for(SimpleIncrementer incrementer : simpleIncrementerList) { | |
incrementer.start(); | |
} | |
Thread.sleep(1000); | |
for(SimpleIncrementer incrementer : simpleIncrementerList) { | |
incrementer.stopIncrementing(); | |
} | |
for(SimpleIncrementer incrementer : simpleIncrementerList) { | |
incrementer.join(); | |
} | |
long countTillNow = 0; | |
for(SimpleIncrementer incrementer : simpleIncrementerList) { | |
countTillNow += incrementer.count(); | |
} | |
System.out.println(countTillNow); | |
System.out.println(counter.count()); | |
Assert.assertEquals(true, countTillNow == counter.count()); | |
} | |
private class SimpleLongCounter { | |
private long count = 0; | |
public long count() { | |
return count; | |
} | |
public void increment() { | |
count++; | |
} | |
} | |
private class SimpleIncrementer extends Thread { | |
private long trackCount = 0; | |
private final SimpleLongCounter counter; | |
private volatile boolean stopProcessing = false; | |
public SimpleIncrementer(SimpleLongCounter counter) { | |
this.counter = counter; | |
} | |
public long count() { | |
return trackCount; | |
} | |
@Override | |
public void run() { | |
while(!stopProcessing) { | |
trackCount++; | |
counter.increment(); | |
} | |
} | |
public void stopIncrementing() { | |
stopProcessing = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment