Created
April 3, 2012 14:27
-
-
Save raheelahmad/2292420 to your computer and use it in GitHub Desktop.
Implementing synchronized methods in shared data
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
import java.util.Random; | |
class Counter { | |
private int c=0; | |
public synchronized void increment() { | |
c++; | |
} | |
public synchronized void decrement() { | |
c--; | |
} | |
public synchronized int value() { | |
return c; | |
} | |
} | |
class Runner implements Runnable { | |
Counter counter; | |
public Runner(Counter ctr) { | |
counter = ctr; | |
} | |
public void run() { | |
int c = 0; | |
while (c++ < 1000000) | |
if (c % 200 == 0) | |
counter.decrement(); | |
else if (c % 50 == 0) | |
counter.increment(); | |
else if (c % 5 == 0) | |
System.out.println(counter.value()); | |
} | |
} | |
public class CheckingSync { | |
public static void main(String[] args) { | |
Counter ctr = new Counter(); | |
Thread t1 = new Thread(new Runner(ctr)); | |
Thread t2 = new Thread(new Runner(ctr)); | |
t1.start(); | |
t2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment