following code gives AABB as out put .but since public void run is synchronized i am expecting ABAB as out put.because synchronized method can access by only one thread at a time .Am i correct or plese explain the theory and reason for this output
You are correct that even when a thread sleeps it doesn't give up the locks it has acquired. The problem in this case is that each thread can execute the run() method concurrently, since there are two locks at play (one for each thread.) When you have a synchronized method you acquire the lock of the object used to invoke the method, and in this case we have two objects (each of the threads,) so concurrent execution is not a problem.
All code in my posts, unless a source is explicitly mentioned, is my own.
Here you have two different objects lock that will be taken by two thread. If one thread object would have been shared between two threads than your output would be right. That will happen in this case:
Asanka it is a simple concept. Let me try to explain it to you. Let's take a simple example first to make the basics clear
Here you are creating two separate instances of MyThread and calling start on them. So the output will be AB or BA. I think this would be clear. Now let's modify the code a bit-
Now the output can be ABAB (it can vary though). Now if I synchronize the run method. That would make no difference. This is because m1 and m2 are separate instances of MyThread. So they will not block each other. Let's take another example for this.
Now the output will be abab. This is because both the threads t1 and t2 share the same instance of MyRunnable. So they both can call method one at a time. But if both the threads had different instances of MyRunnable, then they could be able to call method at the same time. This is reflected in the code below
Now you can see that there are two separate instances of MyRunnable. So the output will be aabb. I hope you will get it this time as it is very difficult to explain
Here whey you call Tg a=new Tg(); a new lock for object a will be created say LockForA. when you call t1.start(); it will try to get the object a's lock that is LockForA. as Thread t1=new Thread(a);, means t1 is running run() method of object a that is synchronized.
when you call t2.start(); it will again try to get the object a's lock that is LockForA, that is already acquired by t1 thread, so it will wait for the lock. When t1 thread will execute the object a's run() method, it will release the lock, so t2 thread will get the lock and start executing the run() method of object a.
If you have any doubt ask...
Joined: Oct 24, 2008
i got the point . thank you ankit and punit for you,r greate explanation