I have written one program where two threads are running that's why i have used synchronized keyword. My code is below-
public class TestThreadAnother {
public synchronized void decrement(){
try {
for (int i = 4; i > 0; i--) {
System.out.println("Thread " + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestThreadClass extends Thread {
private String threadName;
TestThreadAnother obj1;
public TestThreadClass(String threadName, TestThreadAnother Obj1) {
this.threadName = threadName;
obj1 = Obj1;
System.out.println("Creating " + threadName);
}
@Override
public void run() {
System.out.println("Running " + threadName);
obj1.decrement();
System.out.println("End of " + threadName);
}
}
public class TestThreadMain {
public static void main(String[] args) {
TestThreadAnother obj1 = new TestThreadAnother();
TestThreadClass t1 = new TestThreadClass("Thread 1", obj1);
TestThreadClass t2 = new TestThreadClass("Thread 2", obj1);
t1.start();
t2.start();
}
}
The output shoud be -
Creating Thread 1
Creating Thread 2
Running Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
Running Thread 2
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 2
But I am getting the following result-
Creating Thread 1
Creating Thread 2
Running Thread 2
Thread 4
Thread 3
Running Thread 1
Thread 2
Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
End of Thread 2
but my question is as i am using synchronized method then why this is happening? As know if i use synchronized then at first 1st thread will execute and then 2nd one will execute.But in my case sometimes this is not happening. Java Experts need your help regarding this problem.
decrement()
to catch? – Kaplan