一.线程的调度
有两种调度策略:
①时间片策略
在非常短时间内迅速切换执行不同线程
②抢占式策略
高优先级线程抢占cpu
二.线程的优先级
1.线程的优先级等级:
MAX_PRIORITY:10
NORM_PRIORITY:5
MIN_PRIORITY:1
2.如何获取和设置当前线程的优先级:
getPriority(): 获取
setPriority(int p):设置
h1.setPriority(Thread.MAX_PRIORITY);
h1.start(); //设置需在start()之前
说明:
高优先级的线程抢占低优先级的线程的cpu的执行权,但只是从概率上讲,高优先级的线程高概率情况下被执行
-
并不意味只有当高优先级线程执行后,低优先级才执行
下面来举一个栗子:
package test;
/*
建立三个窗口买100张票
*/
import sun.plugin2.os.windows.Windows;
public class Window implements Comparable<Window>{
public static int ticket = 100;
static class Windows implements Runnable {
@Override
public void run() {
while(true){
if (ticket>0){
System.out.println(Thread.currentThread().getName() + ":买票,票号为:" + ticket);
ticket--;
}else {
break;
}
}
}
}
public static void main(String[] args) {
Windows w = new Windows();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.setPriority(Thread.MAX_PRIORITY); //此处设置了t2的优先级为最高
t2.start();
t3.start();
}
@Override
public int compareTo(Window o) {
return this.ticket-o.ticket;
}
}
注:
上面的栗子中,我们在start之前设置了t2的优先级为最高,则在程序执行时,就会优先考虑执行t2这个线程,但并不是绝对的只执行t2,也并非全部执行完t2才执行其他的线程,只是提高了t2线程优先执行的概率