Created
February 1, 2015 21:37
-
-
Save revox/265bfb56902c2cce656d to your computer and use it in GitHub Desktop.
Shows synchronized shared data access
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 characters
| class counterThreadSynchronized | |
| { | |
| static Counter count = new Counter(); | |
| static class t1 extends Thread | |
| { | |
| public void run() | |
| { | |
| for (int i=0;i<50000;i++) { | |
| count.increment(); | |
| } | |
| System.out.println("t1 " + count.value()); | |
| } | |
| } | |
| static class t2 extends Thread | |
| { | |
| public void run() | |
| { | |
| for (int i=0;i<50000;i++) { | |
| count.increment(); | |
| } | |
| System.out.println("t2 " + count.value()); | |
| } | |
| } | |
| public static void main(String [] args) | |
| { | |
| new t1().start(); | |
| new t2().start(); | |
| } | |
| } | |
| class Counter { | |
| private int c = 0; | |
| public synchronized void increment() { | |
| c++; | |
| } | |
| public synchronized int value() { | |
| return c; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment