线程的priority能告诉调度程序其重要性如何,今天我们通过实例来学习一下java多线程中的关于优先级的知识。我从没被谁知道,所以也没被谁忘记。在别人的回忆中生活,并不是我的目的。
java多线程的优先级
一、java多线程中关于优先级的实例
package com.linux.huhx.thread1;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class PriorityThread extends Thread {
PriorityThread(String name, int priority) {
super(name);
setPriority(priority);
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println(Thread.currentThread().getName() + ", " + i + ", priority = " + Thread.currentThread().getPriority());
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试的主体类内容如下:
package com.linux.huhx.thread1;
public class PriorityThreadTest {
public static void main(String[] args) {
PriorityThread thread1 = new PriorityThread("T-1", Thread.NORM_PRIORITY);
PriorityThread thread2 = new PriorityThread("T-2", Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}
一次的运行结果如下:
T-2, 0, priority = 10
T-1, 0, priority = 5
T-2, 1, priority = 10
T-2, 2, priority = 10
T-1, 1, priority = 5
T-1, 2, priority = 5
T-1, 3, priority = 5
T-2, 3, priority = 10
T-1, 4, priority = 5
T-1, 5, priority = 5
T-2, 4, priority = 10
T-2, 5, priority = 10
T-2, 6, priority = 10
T-1, 6, priority = 5
T-2, 7, priority = 10
T-1, 7, priority = 5
T-1, 8, priority = 5
T-1, 9, priority = 5
T-2, 8, priority = 10
T-2, 9, priority = 10
尽管处理器处理现有线程集的顺序是不确定的,但是如果有许多线程被阻塞并在等待运行,那么调度程序将倾向于让优先权最高的线程先执行。
友情链接
https://www.cnblogs.com/huhx/tag/java/default.html