Hi friends,
This is regarding synchronization in Thread. If a block or method is synchronized, which object is said to be synchronization?

as per my knowledge..

it may be any class's object...


synchronize(object)
{


}

object may be current class or any other class that need to run
synchronously with current class...

Thanks. In the following code, which object is synchronized?

public class TestThread implements Runnable
{
	TestThread()
	{
		new Thread(this,"Test 1").start();
		new Thread(this,"Test 22").start();
	}

	synchronized public void run()
	{
		int i=0;
		do
		{
			System.out.println((i++)+"....Sync block 1 :"+Thread.currentThread().getName());
		}while(i<3);
	}

	public static void main(String[] args) throws InterruptedException
	{
		new TestThread();
	}
}

this will be the object as default...

if you got the point...

mark it resolved..

Its seems to be that method's(run) object and not this. Following is the statement taken from
http://www.javaworld.com/javaworld/jw-04-1996/jw-04-synch.html

During the execution of a synchronized method, the thread holds the monitor for that method's object, or if the method is static, it holds the monitor for that method's class. If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor (by either exiting the method or by calling wait()).

Sorry ramjeev, musthafa is right. "this" is the method's object.

See Java Lanmguage ref:

8.4.3.6 synchronized Methods
A synchronized method acquires a monitor (ยง17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

Sorry ramjeev, musthafa is right. "this" is the method's object.

See Java Lanmguage ref:

For Static mtd, object of that class is used.
For Instance mtd, this object is used.

This is what i can understand from your statement.Am I right?

Yes.

Thanks James & Mustafa.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.