forum

Home / DeveloperSection / Forums / Synchronized thread method in java

Synchronized thread method in java

Elena Glibart250129-Oct-2014
I have one question about thread. I have following Thread class and creating 2 thread objects.

publicclassMyThread extends Thread{
 
    String name="";
 
    public MyThread(String string) {
        name=string;
    }   
 
    @Override
    publicvoid run() {
        callMe();
    }        
    synchronized privatevoid callMe() {
        System.out.println("Started");
        for (int i = 1; i <= 5; i++) {
            System.out.println(name+" = "+i);
        }          
    }
 
 
    publicstaticvoid main(String[] args) {                    MyThread a = newMyThread("A");
        MyThread b = newMyThread("B");
 
        a.start();
        b.start();
    }       }

Output:

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 keyword.


Updated on 29-Oct-2014

Can you answer this question?


Answer

1 Answers

Liked By