优先级(priority):在多个线程同时执行时,线程的调度器会根据线程的优先级,优先调用级别高的线程,优先调用不代表绝对的前后顺序,线程级别高的先调用的概率就大,线程级别低的先调用的概率就小,就相当买彩票,优先级低的相当买一张彩票,优先级高的相当于买一百张,所以优先级只代表一个概率大小。
练习:
package com.cb.thread.day02;
/*
* 线程的优先级1-10
* 1. NORM_PRIORITY 5 默认
* 2. MIN_PRIORITY 1
* 3. MIN_PRIORITY 10
*/
public class PrioritTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
MyPriority mp = new MyPriority();
Thread t1 = new Thread(mp);
t1.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+""+Thread.currentThread().getPriority());
}
}
运行结果:默认的优先级是5
练习二:
package com.cb.thread.day02;
/*
* 线程的优先级1-10
* 1. NORM_PRIORITY 5 默认
* 2. MIN_PRIORITY 1
* 3. MIN_PRIORITY 10
*
* 概率,不代表绝对的先后顺序
*/
public class PrioritTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
MyPriority mp = new MyPriority();
//设置优先级在启动线程之前
Thread t1 = new Thread(mp,"NIKE");
Thread t2 = new Thread(mp,"adidas");
Thread t3 = new Thread(mp,"李宁");
Thread t4 = new Thread(mp,"安踏");
Thread t5 = new Thread(mp,"特步");
Thread t6 = new Thread(mp,"匹克");
//优先级只能1-10之间, 前三优先级1,后三个优先10
t1.setPriority(Thread.MIN_PRIORITY);;
t2.setPriority(1);
t3.setPriority(Thread.MIN_PRIORITY);;
t4.setPriority(Thread.MAX_PRIORITY);
t5.setPriority(10);
t6.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
Thread.yield();
}
}
运行结果1:
运行结果2:
从结果上可以看出来优先级不是100%的从高到低。