Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.1k points)

I have done some research regarding multithreading. And I am listing down below what I know:

The moment start() is called with an object of thread class, this thread goes to running state.

In this way, all of the threads go to a running state when the start() is called by the object of those threads. This is a JVM thread scheduler, it picks running state threads. And the call stack for that thread gets executed.  

If the JVM thread scheduler picks up that thread from running state to runnable state, it can stop the execution. 

I want to ask that for a multiprocessor machine, how JVM thread scheduler picks thread from the Runnable state? 

This is the code I have written:

// Class of main thread

public class ThreadMain {

    public static void main(String[] args) {

        Runnable threadJob=new MyRunnable();

        Thread t=new Thread(threadJob);

        t.start();

        System.out.println("Back in the Main");

    }

}

// Class of another thread

public class MyRunnable implements Runnable{

    public void run()

    {

        System.out.println("I'm Thread");

    }

}

There are two threads over here. Main thread, and the one I've created. If my machine has a multiprocessor, how will it behave if I have a multiprocessor in my machine?

1 Answer

0 votes
by (11.7k points)

In Java, JVM thread scheduler is valid only if we take into consideration operating systems, JVM and class library as an execution environment as a whole. Then it is sure that this kind of environment has a scheduler, no matter how it’s been implemented.    

The latest implementations of the JVM will create an operating system level thread for each Java thread and does not perform scheduling related activity itself. There can be a chance that JVM implementation may contain a scheduler for OS that do not have one. 

Whenever you test any program, a second thread can be assigned to a different core by OS. But this program is small, so there is a possibility of the termination of the first thread even before the second thread starts. it will likely run on the same core as the first, but there is no guarantee about any particular scheduling behavior at all.

But there is no surety regarding the behaviour of a particular scheduling, most SMP libraries and tools are built on the assumption that if there are enough runnable threads with sufficient workload, these threads are available to CPU cores by the underlying system.

Browse Categories

...