线程的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-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
T-, , priority =
尽管处理器处理现有线程集的顺序是不确定的,但是如果有许多线程被阻塞并在等待运行,那么调度程序将倾向于让优先权最高的线程先执行。
友情链接
- 关于java中多线程优先级的博客:http://www.cnblogs.com/wuyudong/p/java-multithreading8.html