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:
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
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 } }
JavaRace is running
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(); } }
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.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc