Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Created April 3, 2012 14:27
Show Gist options
  • Save raheelahmad/2292420 to your computer and use it in GitHub Desktop.
Save raheelahmad/2292420 to your computer and use it in GitHub Desktop.
Implementing synchronized methods in shared data
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