---
title: "Synchronized thread method in java"  
description: "Synchronized thread method in java"  
author: "Elena Glibart"  
published: 2014-10-29  
updated: 2014-10-29  
canonical: https://www.mindstick.com/forum/2456/synchronized-thread-method-in-java  
category: "java"  
tags: ["java", "thread", "multiple threading"]  
reading_time: 2 minutes  

---

# Synchronized thread method in java

I have [one question](https://answers.mindstick.com/qa/36489/what-one-question-tells-you-the-most-about-someone) about thread. I have following Thread [class](https://www.mindstick.com/blog/165/generic-class-in-c-sharp) and creating 2 thread objects.

```
public class MyThread extends Thread{     String name="";     public MyThread(String string) {        name=string;    }         @Override    public void run() {        callMe();    }      
     synchronized private void callMe() {        System.out.println("Started");        for (int i = 1; i <= 5; i++) {            System.out.println(name+" = "+i);        }               }      public static void main(String[] args) {           
        MyThread a = new MyThread("A");        MyThread b = new MyThread("B");         a.start();        b.start();    }      
}
```

**[Output](https://www.mindstick.com/interview/34427/explain-the-output-in-angular):**\

Started

Started

B = 1

B = 2

A = 1

A = 2

B = 3

A = 3

B = 4

A = 4

B = 5

A = 5

my question is: why loop is NOT executed one after other? I have used [synchronized](https://www.mindstick.com/interview/2499/what-is-the-purpose-of-synchronized-block) keyword.\

## Replies

### Reply by marcel ethan

Your synchronized method is effectively:

```
private void callMe() {    synchronized(this) {        System.out.println("Started");        for (int i = 1; i <= 5; i++) {            System.out.println(name+" = "+i);        }    }}
```

Now you've created two different instances, so this will be different for each thread... so they're not synchronizing against each other. If you want to see two threads working with the same monitor, you could rewrite your code like this:\

```
public final class DemoRunnable implements Runnable {    @Override    public synchronized void run() {        System.out.println("Started");        for (int i = 1; i <= 5; i++) {            System.out.println(Thread.currentThread().getName() + " = " + i);        }    }     public static void main(String[] args) {        Runnable runnable = new DemoRunnable();        Thread a = new Thread(runnable, "A");        Thread b = new Thread(runnable, "B");        a.start();        b.start();    }}
```

**Output:**\

Started

A = 1

A = 2

A = 3

A = 4

A = 5

Started

B = 1

B = 2

B = 3

B = 4

B = 5


---

Original Source: https://www.mindstick.com/forum/2456/synchronized-thread-method-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
