Skip to content

Instantly share code, notes, and snippets.

@muety
Created July 6, 2016 07:23
Show Gist options
  • Save muety/26dde186b7650caa81b597591c936e2e to your computer and use it in GitHub Desktop.
Save muety/26dde186b7650caa81b597591c936e2e to your computer and use it in GitHub Desktop.
public class ConcurrentCounterSample {
public static void main(String[] args) throws InterruptedException {
final int NUM_THREADS = 2;
MyCounter counter = new MyCounter();
Thread[] threads = new Thread[NUM_THREADS];
int i;
long startTime = System.currentTimeMillis();
for (i = 0; i < NUM_THREADS; i++) {
Thread thread = new Thread(new CounterIncRunnable(counter));
thread.start();
threads[i] = thread;
}
System.out.println(i + " Threads started.");
for (i = 0; i < NUM_THREADS; i++) {
threads[i].join();
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Elapsed Time: " + elapsedTime + " ms");
System.out.println("Counter value: " + counter.value());
}
}
class CounterIncRunnable implements Runnable {
private MyCounter counter;
public CounterIncRunnable(MyCounter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 10000000; i++) {
counter.increment();
}
}
}
class MyCounter {
private int c = 0;
/* Remove the synchronized keyword to run into race conditions */
public synchronized void increment() {
c++;
}
public int value() {
return c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment