If I have a synchronized method and two threads are waiting to enter it they seem to enter the thread Last In First Executed. Is there a way to make this First In First Executed?
This is the unit test that I'm using:
package com.test.thread;
import org.apache.log4j.Logger;
import org.junit.Test;
public class ThreadTest {
private static final Logger log = Logger.getLogger(ThreadTest.class);
@Test
public void testThreading() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() { synchd("1"); }
});
Thread t2 = new Thread(new Runnable() {
public void run() { synchd("2"); }
});
Thread t3 = new Thread(new Runnable() {
public void run() { synchd("3"); }
});
t3.start();
Thread.sleep(5);
t1.start();
t2.start();
Thread.sleep(12000);
}
public static synchronized void synchd(String output) {
log.debug(output);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// do nothing
}
}
}
The output for this is always 3, 2, 1, and I'd like to find a way for it to be 3, 1, 2.
No, they are not executed in their order of arrival.
The execution order depends on lots of parameters relative to threads scheduling and is most often unpredictable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With