Last active
August 29, 2015 14:14
-
-
Save revox/ce6dc504a12dec10e140 to your computer and use it in GitHub Desktop.
Thread interference example
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 counterThreadClash | |
| { | |
| 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 void increment() { | |
| c++; | |
| } | |
| public void decrement() { | |
| c--; | |
| } | |
| public int value() { | |
| return c; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment