Java Thread-Scheduler:

When the computer system having more and more processors, then threads often share one or more processors. The JVM decipher how to share the processor resource among threads, so this is a task which is known as thread scheduling. The portion of JVM that is able to perform thread scheduling is thread scheduler.

It is a part of the JVM that decides which thread should execute first then which thread should execute next and so on. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.

Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. It is noted that once a thread start its execution then it can never started again. If we start the thread again then an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. Let's understand it by the example given below:

Example

public class MyThread extends Thread
{
public void run()
{
System.out.println("JavaRace is running");
}
public static void main(String args[])
{
MyThread t1=new MyThread();
t1.start();
t1.start();
}
}

Output

JavaRace is running
Exception in thread "main" java.lang.IllegalThreadStateException

Note:

  • For each thread, a separate stack will be created.
  • If we invoke run() method directly by thread instance then the run() method goes onto the current call stack rather than at the beginning of a new call stack.

Example

class RunDemo extends Thread
{
public void run()
{
System.out.println("JavaRace is running");
}
public static void main(String[] args)
{
RunDemo r1=new RunDemo1();
r1.run();
//fine, but does not start a separate call stack }
}

Output

JavaRace is running

Problem if you direct call run() method:

Example

class RunDemo1 extends Thread
{
public void run()
{
for(int i=1;i<4;i++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
RunDemo1 r1=new RunDemo1();
RunDemo1 r2=new RunDemo1();
r1.run();
r2.run();
}
}

Output

1
2
3
1
2
3

As you can see in the above program that there is no context-switching because here r1 and r2 will be treated as normal object not thread object.

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment