class ThreadSafeClass extends Thread
{
private static int count = 0;
public synchronized static void increment()
{
count++;
}
public
As explained in other answers, your code is not Thread safe since static method increment()
locks Class monitor and non-static method decrement()
locks Object monitor.
For this code example, better solution exists without synchronzed
keyword usage.
You have to use AtomicInteger to achieve Thread safety.
Thread safe using AtomicInteger
:
import java.util.concurrent.atomic.AtomicInteger;
class ThreadSafeClass extends Thread {
private static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.incrementAndGet();
}
public static void decrement() {
count.decrementAndGet();
}
public static int value() {
return count.get();
}
}