This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Java in General and the fly likes Synchronized Thread doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Synchronized Thread doubt" Watch "Synchronized Thread doubt" New topic

Synchronized Thread doubt

Anudeep Duvvuri

Joined: May 18, 2012
Posts: 29
package may25th;

class Synchr extends Thread {
synchronized void method1() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.out.println("method1-------" + i+ " "+Thread.currentThread().getName());

synchronized void method2() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.out.println("method2-------" + i+" "+Thread.currentThread().getName());

public void run() {
try {
} catch (InterruptedException e1) {
try {
} catch (InterruptedException e) {

public class ThreadSynch2 {
public static void main(String[] args) {
Synchr s = new Synchr();
Synchr s1 = new Synchr();



The ooutput of the above program is
method1-------0 one
method1-------0 two
method1-------1 one
method1-------1 two
method1-------2 one
method1-------2 two
method1-------3 one
method1-------3 two
method1-------4 one
method1-------4 two
method2-------0 one
method2-------0 two
method2-------1 one
method2-------1 two
method2-------2 one
method2-------2 two
method2-------3 one
method2-------3 two
method2-------4 one
method2-------4 two

I could not understand why thread 2 is called before one completes even though the method is synchronized.
Sorry if there was any mistake in this
Please clarify me
Alexei Kaigorodov

Joined: Feb 24, 2008
Posts: 17
In order to synchronize 2 threads, the synchronized object must be the same. In your code, each thread is synchronizing on its own Thread object, which is meaningless.
Anudeep Duvvuri

Joined: May 18, 2012
Posts: 29
ya i got it after posting here thank you for your reply
I agree. Here's the link:
subject: Synchronized Thread doubt
It's not a secret anymore!