Can you explain how Scheduling and Priority works in threads?
Threads are assigned priorities that the thread scheduler can use to determine how the threads will be treated. The thread scheduler can use thread priorities to determine which thread gets to run. Priority of a thread can be set by using the setPriority() method and read by using getPriority()method, both of which are defined in Thread class. JVM selects to run a Runnable thread with the highest priority. All Java threads have a priority in the range 1-10.Top priority is 10, lowest priority is 1.Normal priority i.e. Priority by default is 5.The code below sets the priority of the thread myThread to the minimum of two values: Maximum priority and current priority incremented to the next level.
myThread.setPriority(Math.min(Thread.MAX_PRIORITY, myThread.getPriority()+1);
Most operating system used two types of scheduling:
1. Preemptive scheduling
2 .Time-slicing
public class Scheduler extends Thread
{
public Scheduler()
{
timeSlice = DEFAULT_TIME_SLICE;
queue = new Circularlist();
}
public Scheduler(int quantum)
{
timeSlice = quantum;
queue = new Circularlist();
}
public addThread(Thread t)
{
t.setPriority(2);
queue.additem(t);
}
private void schedulerSleep()
{
try
{
thread.sleep(timeSlice );
}
catch (InterruptedException e){};
}
public void run()
{
Thread current;
this.setpriority(6);
while (true)
{
// get the next thread
current = (Thread)qeue.getnext();
if ( (current != null) && (current.isAlive()) )
{
current.setPriority(4);
schedulerSleep();
current.setPriority(2)
}
}
}
private CircularList queue;
private int timeSlice;
private static final int DEFAULT_TIME_SLICE = 1000;
}
public class TesScheduler
{
public static void main(String args[])
{
thread.currentThread().setpriority(Thread.Max_Priority);
schedular CPUSchedular = new Scheduler ();
CpuSchedular.start()
TestThread t1 = new TestThread("Thread 1");
t1.start()
CpuSchedular.addThread(t1);
TestThread t2 = new TestThread("Thread 2");
t2.start()
CpuSchedular.addThread(t2);
TestThread t3 = new TestThread("Thread 1");
t3.start()
CpuSchedular.addThread(t3);
}
}