What are synchronized methods and synchronized statements?

What are synchronized methods and synchronized statements?

Synchronized Methods:When a method in Java needs to be synchronized, the keyword synchronized should be added.

Example:
Public synchronized void increment()
{
X++;
}

Synchronization does not allow invocation of this Synchronized method for the same object until the first thread is done with the object. Synchronization allows having control over the data in the class.

Synchronized Statement:
A synchronized Statement can only be executed once the thread has obtained a lock for the object or the class that has been referred to in the statement. Synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized.

Example:
public void run()
{
synchronized(p1)
{ //synchronize statement. P1 here is an object of some class P
p1.display(s1);
}
}

What are synchronized methods and synchronized statements?

Synchronized Methods:

Two invocations of synchronized methods cannot interleave on the same object.

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Synchronized statements:

Another way to create synchronized code is with synchronized statements. Synchronized statements must specify the object that provides the intrinsic lock:
public void add(String str)
{
      synchronized(this)
      {
      str1 = str;
      cnt++;
      }
     strList.add(str);
}

What are synchronized methods and synchronized statements?

Synchronized Methods:
Two synchronized methods cannot interleave on the same object.
When a thread of a synchronized method is executing on an object, the other threads invoking synchronized methods on that object are suspended until the first thread has finished.

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors

Synchronized statements provide finer synchronization than the synchronized methods.
What is a monitor?
What is a monitor? - A monitor works as a lock on the data item. When a thread holds the monitor for some data item, other....
How do we allow one thread to wait while other to finish?
How do we allow one thread to wait while other to finish - Using the join() method, one can allow one thread to wait while other to finish....
Explain the purpose of yield method.
Explain the purpose of yield method - Yield method causes the currently executing thread object to temporarily pause and allow other threads to execute....
Post your comment