why synchronized method is not working for multithread
java, multithreading, synchronized
Solution
The output is correct. Only your `decrement()` method is synchronized. This means that the `decrement()` method of this object can't be called by more than one thread at a time. But that doesn't prevent other threads from doing something else while one thread is executing `decrement()`.
Your output shows that while thread 2 is executing `decrement()`, thread 1 is executing the first `System.out.println()` in the `run()` method, then possibly waits for thread 2 to have completed its call to `decrement()`, then executes `decrement()`.
Problem
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.