For synchronized block, an object has been passed.The question is,Why & when it is passed & what is the purpose of passing an object?

-Thanks in advance

Recommended Answers

All 15 Replies

That is the instance that all threads must obtain a lock on in order to access the block.

That is the instance that all threads must obtain a lock on in order to access the block.

Can u explain in detail,if possible?

Is 'synchronized block' is equivalent synchronized method? Its seems to be the same when i tried with a sample.Can u help on this.

public class TestThread implements Runnable
{
	static Thread t1,t2;

	TestThread()
	{
		System.out.println("Hello World! ");
		int a1=0,a2=0;

		t1 = new Thread(this,"Test 1");
		t2 = new Thread(this,"Test 22");

		t1.start();
		t2.start();
	}

	void Check()
	{
		int i=0;
		//synchronized(System.in)  //Behaves as syn. mtd
		//synchronized(t1)              //Behaves as syn. mtd
                synchronized(t2)                 //Behaves as syn. mtd
		{
			while(true)
			{
				if(i<20)
					System.out.println(i+"....Sync block  :"+Thread.currentThread().getName());
				else
					break;
				i++;
			}
		}
	}

	public void run()
	{
		System.out.println("Run : "+Thread.currentThread().getName());
		Check();
	}

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

It depends on what you're synchronising on. I can say now, however, that synchronising on the thread, is just plain wrong.

the whole concept of synchronization comes when we know that the data is going to be shared by multiple users .

synchronization of block is different from synchronization of function because a sync. block can come under a function ....means one should use sync block when he wants to sync some part of the function and not the whole function.....
as in your code u sync the object with a limited code and not the whole code......


sync. of whole object or a func slows the execution speed of program

the whole concept of synchronization comes when we know that the data is going to be shared by multiple users .

synchronization of block is different from synchronization of function because a sync. block can come under a function ....means one should use sync block when he wants to sync some part of the function and not the whole function.....
as in your code u sync the object with a limited code and not the whole code......


sync. of whole object or a func slows the execution speed of program

You'll notice, he has the entire body of the method synced (except the declaration of the variable, whoopee!). So what determines whether that is better or not depends on what is being synced on. Syncing on "this" is, effectively, the same as simply syncing the method. Now, if each synced block syncs on different objects, then time can be saved, but be very careful or deadlocks are a very real possibility, more like a probability, if not an ensurity.

Thanks.
Actually,my question is to know the purpose of object.

synchronized(t1) 
synchronized(t2)

For anyone of the above, I get the same result.If it is so,then syn. block prototype should be 'synchronized()'. i.e,with passing any parameters.

As far as Output is concerned,
Whichever runs first, it finishes it round upto 20.Then left the other to start & complete its 20.

Like I said, do not sync on the thread. It makes no sense. Create an instance variable of type Object and sync on that.

As far as Output is concerned,
Whichever runs first, it finishes it round upto 20.Then left the other to start & complete its 20.

Well, seeing as how you've synced around the entire while statement, so that only one thread at a time can access the entire loop, what did you expect? If what you really want is to have the print statement mixed, then sync only around the println statement.

Thanks.
Actually,my question is to know the purpose of object.

synchronized(t1) 
synchronized(t2)

For anyone of the above, I get the same result.If it is so,then syn. block prototype should be 'synchronized()'. i.e,with passing any parameters.

As far as Output is concerned,
Whichever runs first, it finishes it round upto 20.Then left the other to start & complete its 20.

when u write synchronized(t1), the object t1 will be synchronized.But when we sync a block or a function,not the whole object but a part of it will be sync.

No the "object t1" is not synced. The object in the sync call block is what threads will attempt to lock in order to execute the block, the object itself is irrelevant as long as all threads attempt to sync on the same object. I don't know what you were really trying to say in that post, but how much is "synced" depends purely on what the block encompasses, and how "parallel" something is depends largely on how many different synced blocks lock on the same object. I.E. two blocks that both sync on object "a" will block each other, whereas if one of them syncs on "b" they do not block each other.

Now, it seems to be clear.

void Check()
	{
		int i=0;
		int j=0;

		synchronized(t1)
		{
			while(true)
			{
				if(i<5)
					System.out.println(i+"....Sync block t1 :"+Thread.currentThread().getName());
				else
					break;
				i++;
			}
		}
		synchronized(t2)
		{
			while(true)
			{
				if(j<5)
					System.out.println(j+"....Sync block t2 :"+Thread.currentThread().getName());
				else
					break;
				j++;
			}
		}
	}

And the output is like this, which makes each sync block parallel.

Run : Test 1
Run : Test 22
0....Sync block t1 :Test 1
1....Sync block t1 :Test 1
2....Sync block t1 :Test 1
3....Sync block t1 :Test 1
4....Sync block t1 :Test 1
0....Sync block t2 :Test 1
0....Sync block t1 :Test 22
1....Sync block t2 :Test 1
1....Sync block t1 :Test 22
2....Sync block t2 :Test 1
2....Sync block t1 :Test 22
3....Sync block t2 :Test 1
3....Sync block t1 :Test 22
4....Sync block t2 :Test 1
4....Sync block t1 :Test 22
0....Sync block t2 :Test 22
1....Sync block t2 :Test 22
2....Sync block t2 :Test 22
3....Sync block t2 :Test 22
4....Sync block t2 :Test 22

No, it's not sync at all. You just as well remove the sync blocks as they are doing nothing. I have said time and again, do not sync on the thread, that makes no sense, and if you want the print statements mixed than sync only around the print statement and not around the entire while loop. And create an instance variable of type Object and instantiate it and sync on that.

The concept is not that hard, but, seeing as how you haven't been able to follow directions, yet, even when explicitly stated:

public class TestThread implements Runnable {
    final Object lock = new Object();

    TestThread() {
        System.out.println("Hello World! ");
        new Thread(this,"Test 1").start();
        new Thread(this,"Test 22").start();
    }

    void Check() {
        for (int i = 0; i < 20; i++) {
            synchronized(lock) {
                System.out.println(i +  " .... Sync block:  " + Thread.currentThread().getName());
            }
        }
    }

    public void run() {
        System.out.println("Run : " + Thread.currentThread().getName());
        Check();
    }

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

Thanks for your patience explanation, Masijade.
I can understand the concept now.It takes time for me to take up and sorry for the same.Really good effort to make this clear.Thanks, once again.

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.