线程的优先级

线程的优先级

一、关于线程生命周期中的JVM调度

  • 线程的优先级是可以设置的,优先级较高的,获得CPU时间片的总体概率高一些。
  • JVM采用的是抢占式调度模型。谁的优先级高,获取CPU时间片的总体概率就高。
  • 默认情况下,一个线程的优先级是 5。
  • 最低是1,最高是10。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.camellia.thread.ThreadPriority;

import org.junit.jupiter.api.Test;

public class ThreadPriorityTest {
public static void main(String[] args) {
System.out.println("线程最低优先级:"+Thread.MIN_PRIORITY);
System.out.println("线程的最高优先级"+Thread.MAX_PRIORITY);
System.out.println("线程的默认优先级"+Thread.NORM_PRIORITY);
}

@Test
public void testThreadPriority() {
//获取main线程的优先级
Thread mainThread = Thread.currentThread();
System.out.println("main线程的优先级"+mainThread.getPriority());
//设置优先级
mainThread.setPriority(Thread.MAX_PRIORITY);
System.out.println("main线程的优先级"+mainThread.getPriority());
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.camellia.thread.ThreadPriority;

public class SetThreadPriority {
public static void main(String[] args) {
Thread thread1 = new MyThread();
Thread thread2 = new MyThread();
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
//总体thread1抢到时间片几率更大,执行更靠前。
}
}

class MyThread extends Thread {
@Override
public void run() {
for (int i=0;i<1000;i++) {
System.out.println(Thread.currentThread().getName() +"\t"+ i );
}
}
}