-
-
Save AlexRogalskiy/cb6b27a2e7f246b4f0f42f0c90a3cdc7 to your computer and use it in GitHub Desktop.
Revisions
-
NicMcPhee revised this gist
Mar 8, 2016 . No changes.There are no files selected for viewing
-
NicMcPhee created this gist
Nov 20, 2013 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,20 @@ public class Counter { private int count = 0; public int getCount() { return count ; } /** * The "synchronized" keyword is crucial here; removing it will lead to serious * race conditions on multiple-core computers. Having it ensures that two threads * can't enter this method at the same time, making sure that only one thread passes * through this method at a time, which ensures that the increments are handled * correctly. */ public synchronized void incrementCount() { ++count; } } This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ public class SynchronizedIncrement implements Runnable { private static final int NUM_THREADS = 4; private static final int NUM_INCREMENTS = 10000; private Counter counter; public SynchronizedIncrement(Counter counter) { this.counter = counter; } public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[NUM_THREADS]; Counter counter = new Counter(); for (int i=0; i<NUM_THREADS; ++i) { threads[i] = new Thread(new SynchronizedIncrement(counter)); threads[i].start(); } for (int i=0; i<NUM_THREADS; ++i) { threads[i].join(); } System.out.println("total count = " + counter.getCount() + " vs. expected = " + (NUM_THREADS * NUM_INCREMENTS)); } @Override public void run() { for (int i=0; i<NUM_INCREMENTS; ++i) { counter.incrementCount(); } } }