/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MyClass
{
public static int count=0;
static boolean lock=false;
boolean getLock()
{
synchronized(this)
{
if(lock==false)
{
lock=true;
return true;
}
else
{
return false;
}
}
}
public int getCount()
{
System.
out.
println("Inside getcount()");
return count;
}
public synchronized void incrementCount()
{
count=count+1;
}
public synchronized void decrementCount()
{
count=count-1;
}
}
class Ideone
{
public static int count=0;
static boolean lock=false;
boolean getLock()
{
synchronized(this)
{
if(lock==false)
{
lock=true;
return true;
}
else
{
return false;
}
}
}
public int getCount()
{
System.
out.
println("Inside getcount()");
return count;
}
public synchronized void incrementCount()
{
int x=count+1;
try {
Thread.
sleep((int) (100 + (Math.
random() * (400 - 5)))); e.printStackTrace();
}
count= x;
}
public synchronized void decrementCount()
{
count=count-1;
}
final MyClass test1 = new MyClass();
final MyClass test2 = new MyClass();
final MyClass test3 = new MyClass();
final MyClass test4 = new MyClass();
public void run()
{
int k=0;
while (k++<5000000)
{
//System.out.println("Thread 1 going to increment count");
test1.incrementCount();
//System.out.println("Thread 1 incremented count");
}
}
};
public void run()
{
int l=0;
while (l++<5000000)
{
//System.out.println("Thread 1 going to increment count");
test2.incrementCount();
//System.out.println("Thread 2 count read = " + c);
}
}
};
public void run()
{
int l=0;
while (l++<5000000)
{
//System.out.println("Thread 1 going to increment count");
test3.incrementCount();
//System.out.println("Thread 2 count read = " + c);
}
}
};
public void run()
{
int l=0;
while (l++<5000000)
{
//System.out.println("Thread 1 going to increment count");
test4.incrementCount();
//System.out.println("Thread 2 count read = " + c);
}
}
};
// Thread t2 = new Thread() { public void run() { test1.testMethod2(); } };
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
//System.out.println(t2.getState());
//int x=500000000+500000000;
//System.out.println(x);
System.
out.
println("count = " + MyClass.
count);
}
}