Skip to content

Instantly share code, notes, and snippets.

@revox
Created February 1, 2015 21:37
Show Gist options
  • Select an option

  • Save revox/265bfb56902c2cce656d to your computer and use it in GitHub Desktop.

Select an option

Save revox/265bfb56902c2cce656d to your computer and use it in GitHub Desktop.
Shows synchronized shared data access
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