Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If two threads are waiting to enter a synchronized method, when the mutex is released do they execute in the order they arrived?

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.

like image 587
Will Avatar asked Aug 05 '11 19:08

Will


1 Answers

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.

like image 150
Vivien Barousse Avatar answered Sep 28 '22 16:09

Vivien Barousse