Synchronization is often cited as a cross-section. Cross section means that only one thread can execute it at a time. It is possible for multiple threads to simultaneously execute synchronization code.
The misconception is that many programmers think the Sync keyword locks up the code it surrounds. But that's not the case. The object, not the code, is locked synchronously. So, if you have a synchronization method in your class, this method can be executed by two different threads at the same time, as long as each thread creates an instance of the class itself.
Refer to the following code:
class Foo extends Thread
{
private int val;
public Foo(int v)
{
val = v;
}
public synchronized void printVal(int v)
{
while(true)
System.out.println(v);
}
public void run()
{
printVal(val);
}
}
class SyncTest
{
public static void main(String args[])
{
Foo f1 = new Foo(1);
f1.start();
Foo f2 = new Foo(3);
f2.start();
}
}
The output produced by the running Synctest is 1 and 3 crossed. If the printval is a cross-section, the output you see can only be 1 or 3, not both. The results of the program's operation prove that two threads are executing the Printval method concurrently, even if the method is synchronized and is not terminated because it is an infinite loop.
To implement the real section, you must synchronize a global object or synchronize the class. The following code gives an example of this.
class Foo extends Thread
{
private int val;
public Foo(int v)
{
val = v;
}
public void printVal(int v)
{
synchronized(Foo.class) {
while(true)
System.out.println(v);
}
}
public void run()
{
printVal(val);
}
}
The above class no longer synchronizes individual class instances but synchronizes the classes. For class Foo, it has only a unique class definition, and two threads are synchronized on the same lock, so only one thread can execute the Printval method.
This code can also be locked by the public object. For example, add a static member to Foo. Two methods can synchronize this object and achieve thread safety.