Java threads New order of threads

advertisements
//Class PrintTask sleeps between0-5 seconds
import java.util.Random;
public class PrintTask implements Runnable{
private final int sleeptime;
private final String taskname;
private final static Random generator= new Random();

public PrintTask(String name)
{
    taskname=name;
    sleeptime=generator.nextInt(5000);

}

public void run()
{
    try
    {
        System.out.printf("%s going to sleep for %d ms.\n", taskname,sleeptime);
        Thread.sleep(sleeptime);

    }
    catch(InterruptedException exception)
    {
        System.out.printf("%s %s\n", taskname,"terminated prematurely due to interruption");
    }
    System.out.printf("%s done sleeping\n",taskname);

}

}

//Creation and start of three threads
import java.lang.Thread;
public class Threads {

public static void main(String[] args) {
    System.err.println("Creating threads");
    Thread  thread1=new Thread(new PrintTask("task1"));
    Thread  thread2=new Thread(new PrintTask("task2"));
    Thread  thread3=new Thread(new PrintTask("task3"));

    thread1.start();
    thread2.start();
    thread3.start();
    System.err.println("Tasks Started. Main Ends. \n");
}

}

Some Results

task2 going to sleep for 320 ms.
task1 going to sleep for 3054 ms.
task3 going to sleep for 1821 ms.
task2 done sleeping
task3 done sleeping
task1 done sleeping

task2 going to sleep for 1338 ms.
task3 going to sleep for 2825 ms.
task1 going to sleep for 3461 ms.
task2 done sleeping
task3 done sleeping
task1 done sleeping

My question is why does the message "task" going to sleep for ** ms, is not appearing in the correct order like this: (sometimes it might appear in the "correct" order)

task1 going to sleep for **** ms.
task2 going to sleep for **** ms.
task3 going to sleep for **** ms.

but it seems to be appearing in a random order. I am new to threading so please answer me as simple as you can. Thank you!


You are creating Threads and send them to some kind of scheduler.

These Threads are started by JVM (or the Operating System) in no special order.

update:

As mentioned by @Braj in the comments, you can influence the execution order by setting the Thread priority.