File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About Synchronization in Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About Synchronization in Threads " Watch "About Synchronization in Threads " New topic

About Synchronization in Threads

MohamedSalim malik

Joined: Feb 04, 2011
Posts: 19
Hey friends , i have this problem with Thread Synchronization. please look at the following class where i created two threads by implementing Runnable interface. in here i can only get the results ABAB, Because
I am using two different threads with two different runnable targets. Am i correct. I only want to know my theory is correct? please somebody tell me.

and The second class , I can get two results as "ABAB" , and "AABB" . am i right? It is because i am using the same runnable target for different Threads . Is my theory correct. or please somebody tell me if the way i understand is wrong. and please forgive my bad use of English.

Sebanti Sanyal
Ranch Hand

Joined: Nov 07, 2011
Posts: 58

It is just the opposite. First example uses two different Runnable targets for the two threads. These two threads can concurrently execute the run() method. Hence, the output can be AABB or ABAB.
The second example uses the same Runnable object while creating two threads. The 'synchronized' keyword actually comes into play here.Once a thread is inside the run() method, the other thread has to wait for the former to complete. Therefore, the output has to be ABAB.
MohamedSalim malik

Joined: Feb 04, 2011
Posts: 19
Wow, I got it now. Thanks a lot Sebanti Sanyal for your Short and Sweet answer. You are awesome
I agree. Here's the link:
subject: About Synchronization in Threads
It's not a secret anymore!