I have one thread question. I have a Thread class and 2 threads of objects are created.
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();
}
}
When I do this, the output I get is
Started
Started
B = 1
B = 2
A = 1
A = 2
B = 3
A = 3
B = 4
A = 4
B = 5
A = 5
I know that A and B are printed randomly when the Thread Scheduler selects it.
But my question is: why is the loop NOT executing one after another? I used the keyword synchronized.
source
share