简体   繁体   中英

Main thread running sequence

Let us consider following is our thread:

public class HeavyWorkRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
        try {
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
     //   TODO
    }
}

And the main method:

public class ThreadRunExample {
     public static void main(String[] args){

            Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
            Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
            System.out.println("Starting Runnable threads");

            t1.start();
            t2.start();
            System.out.println("Doing main heavy processing - START "+Thread.currentThread().getName());
            System.out.println("Runnable Threads has been started");
        }
}

Now the outputs are different at different run times. For example:

Output1 :
Starting Runnable threads
Doing main heavy processing - START main
Doing heavy processing - START t1
Doing heavy processing - START t2
Doing heavy processing - END t2
Runnable Threads has been started
Doing heavy processing - END t1

Output2 :
Starting Runnable threads
Doing main heavy processing - START main
Runnable Threads has been started
Doing heavy processing - START t1
Doing heavy processing - END t1
Doing heavy processing - START t2
Doing heavy processing - END t2

As per my understanding of thread:
1. Only a single thread can run at a time.
2. The system chooses threads randomly to run if priorities are not set.

So, the system should complete the tasks of 'main' thread, then run either t1 or t2. If so, then the output should always contain:
Starting Runnable threads
Doing main heavy processing - START main
Runnable Threads has been started
as the first three lines. I'm not getting what I've missed in my understanding.

The thing is: varies between Operating Systems and their processing queues. This is a lengthy topic, but long story short: When the three threads are on the system queue, the OS let one of them run only a fraction of time (called quantum), and then pushes it to the queue to let other threads run, and so on, to have an illusion of multitasking in single processor-single core architectures. For this, each execution will be different for a myriad of reasons.

If you really want to dive into this topic, just start here link

Only one thread can run at a given time in a single processor, that is true. But the Java Virtual Machine contains a component which is called the Thread Scheduler. This component do choose which thread goes into the processor and which one gets out.

When you start a thread, it will enter the runnable state. When the thread scheduler have a slot for processing time, it will pick one of all the runnable threads (at random if they all have the same priority). The chosen one enters the running state for a few milli seconds before the Thread Scheduler interrupts the processing and places the thread back into runnable state.

A thread is consequently not guaranteed to finish its job before going out of the processor.

When you are experiencing with threads, you should consider that all threads that you have started can run concurrently, at the exact same time, so there is no guaranteed ordering.

What you may want to check is how to make a thread wait on other threads (using the Object.wait() method), but that's far beyond this answer.

If you need to dive into threading in Java, you should consider a specific training or google for online ressources, because this is not obvious at all.

First Let me clear your understanding that Only one thread can run at a given time its true but only for single core processor not for multi cores.

Now Main method is nothing but internally a Thread. Now Threading Scheduling and Time Slicing depends on the OS. So, When you run your program Main method still its in Time Slice and hence System.out.println("Doing main heavy processing - START "+Thread.currentThread().getName()); statement is executed and than furthermore statements.

If you want to change your Output than you have to remove your Main Thread From Time Slice of OS.

So,after t2.start(); use Thread.sleep(1000) and you can check that your either t1 or t2 thread will get Scheduler and going for execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM