学习java基础多线程优先级时,发现按照教程的写法,无论如何设置优先级,低优先级的线程占用的CPU时间并不比高优先级的长多少。
package practice;
public class HiLoPri {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY);
lo.start();
hi.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
lo.stop();
hi.stop();
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread:" + lo.click);
System.out.println("High-priority thread:" + hi.click);
}
}
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
@Override
public void run() {
// TODO Auto-generated method stub
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
执行结果
Low-priority thread:3621884808
High-priority thread:3641550389
可以看到并不高多少,于是尝试修改优先级大小等级
clicker hi = new clicker(Thread.NORM_PRIORITY + 4);
clicker lo = new clicker(Thread.NORM_PRIORITY - 4);
执行结果
Low-priority thread:3362383480
High-priority thread:3680814061
一样并未差多少,于是我想到应该是我的电脑CPU核数大于2线程的缘故,于是增加线程
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY);
clicker lo1 = new clicker(Thread.NORM_PRIORITY - 1);
clicker lo2 = new clicker(Thread.NORM_PRIORITY - 2);
clicker lo3 = new clicker(Thread.NORM_PRIORITY - 3);
clicker lo4 = new clicker(Thread.NORM_PRIORITY - 4);
执行结果
Low-priority thread:3492617737
Low1-priority thread:1371754450
Low2-priority thread:1371994714
Low3-priority thread:46415409
Low4-priority thread:46436207
High-priority thread:3626637091
明显其后的低优先级线程占用时间有了明显的缩短,因此设置优先级线程占用的CPU时间与当前终端的CPU核心数有一定的关系