1.
public class SynchronizedCounter
{
private int c = 0;`
public synchronized void increment()
{
c++;
}
public synchronized void decrement()
{
c--;
}
public synchronized int value()
{
return c;
}
}
2.
public class MyThread extends Thread
{
private int threadId;
private final static Object obj = new Object();
public MyThread(int threadId)
{
this.threadId = threadId;
}
@Override
public void run()
{
synchronized (obj)
{
for (int i = 0; i < 1000; i++)
System.out.println(this.threadId);
}
}
}
I would like to present my reasoning and ask you to indicate whether it is correct.
Ex 1 All 3 methods are synchronized. They are non-static and synchronized on a given instance of that class. This means that if we have an object c1 of class SynchronizedCounter then if thread1 executes, for example, the increment method then this method as well as all other synchronized methods are blocked for other threads, other threads cannot call these methods at the same time.
Ex 2 Here we are blocking the body of the run method on the final, importantly, static obj object. By virtue of being static, it is a property of the class, and therefore shared by all objects of that class, static obj is a common monitor for all instances of MyThread. So if thread1 calls the run method it will block it on the obj object. And since the obj object is static ,this means that no other threads will not be able to call this method until the thread that blocked it unblocks it.