The ouput is like that because the JVM has been written to do that But I'm sure that's not what you intend to ask.
Can you explain what you understood and what the confusion is? The code just displays basic java thread behaviour. So, if you can explain which part of the output is confusing you, I will be able to help you with an explanation.
PS: If you are new to threads, you may want to read an online tutorial. Apart from a lesson on Threads, this will give you a good understanding of Thread.sleep() which, I guess, is creating confusion in this case. Try Sun Trail on Threading and Concurrency.
Joined: Dec 24, 2004
Hi praveen balaji,
Thanks for your reply. My doubt is method1 is synchronized. So I am expecting until Thread1 completes the method1 Thread2 will not enter. Same case for method2 also.But output is showing method1 and method2 allowing both the threads. Why its happen like that.
the reason you are not able to understand the behaviour of the programme is that you are missing the concept of object locking.
"one lock per java object"
when a thread tries to enter a synchronized method or block it first acquires the lock and excutes, if lock is not available (means other thread is already inside that synchronized method or block and excuting), it will go to Runnable state. In your case you are creating two thread object means each thread having own different lock so both of them can enter the synchronized method whenever they get chance to execute. In order to get this problem solved you better use Runnable interface and create multiple threads and call synchronized method.This time you wont get any abnormal behaviour.
well, i answered your question best of my knowledge . Correct me if any of my point given above is wrong.
Joined: Dec 04, 2006
hi murali if you have any more doubts then just mail me or let me know
Joined: Dec 24, 2004
Hi Sanjit Kumar,
Thanks for your reply. You are correct. I got the idea. Thanks for your clarification. [ December 12, 2006: Message edited by: murali chevuri ]