Java中引入了线程调度程序以进行线程调度。
当我们有多个线程时,哪个线程将有机会由线程调度程序决定。
当多个线程正在等待时,线程调度程序将决定执行线程的顺序。
线程调度程序是JVM的一部分。
线程调度程序根据一些优先级调度等待线程,具有高优先级的线程将首先获得机会。
我们不能期望线程调度程序会遵循确切的方法。随jvm的不同而不同。这就是为什么我们无法在多线程概念中分辨出确切的输出。
当多个线程正在等待时,线程调度程序将决定执行线程的顺序。
示例
演示线程调度程序的行为。如下面的示例所示,当我们有多个线程时,我们不能期望确切的执行:
class FirstThread extends Thread{ public void run(){ for(int i=0;i<10;++i){ System.out.println("I am in first thread"); try{ Thread.sleep(1000); } catch(InterruptedException ie){ System.out.println("Exception occurs "); } } } } class SecondThread1{ public static void main(String[] args){ FirstThread ft = new FirstThread(); ft.start(); for(int j=1;j<10;++j){ System.out.println("I am in second thread"); } } }
输出结果
D:\Java Articles>java SecondThread1 I am in second thread I am in first thread I am in second thread I am in second thread I am in second thread I am in second thread I am in second thread I am in second thread I am in second thread I am in second thread I am in first thread I am in first thread I am in first thread I am in first thread I am in first thread I am in first thread I am in first thread I am in first thread I am in first thread
在操作系统中引入了时间片以调度进程。
借助时间片因子,短时运行过程将有机会执行。
任务将执行一段预定义的时间,然后重新进入就绪任务池。
示例
假设我们有两个过程,一个过程耗时1小时,第二个过程耗时15分钟。优先级高的第一个进程然后线程调度程序有机会先执行。如果我们分配3分钟的时间片因子。然后,第一个过程将执行3分钟,然后进入等待状态,然后3分钟后,第二个过程将有机会执行3分钟,然后返回等待状态,然后再次执行第3分钟。然后返回等待状态,直到完成。
时间分割因子的目的仅是一个(即,有机会执行短时间等待过程,并使处理器从长时间执行过程中抽出一段时间)。