下面的代码展示了优先级的作用。高优先级的线程倾向于更快地完成。
public class PriorityDemo {
public static class HightPriority extends Thread {
static int count = 0;
@Override
public void run() {
while(true) {
synchronized (PriorityDemo.class) {
count++;
if(count > 10000000) {
System.out.println("HightPriority is complete");
break;
}
}
}
}
}
public static class LowPriority extends Thread {
static int count = 0;
@Override
public void run() {
while (true) {
synchronized (PriorityDemo.class) {
count++;
if(count > 10000000) {
System.out.println("LowPriority is complete");
break;
}
}
}
}
}
public static void main(String[] args) {
Thread high = new HightPriority();
LowPriority low = new LowPriority();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
}
}
上述代码定义两个线程,分别为
HightPriority设置为高优先级,LowPriority为低优先级。让他们完成相同的工作。也就是把count从0加到10000000。完成后,打印信息给一个提示。在对count 累加前,使用synchronized产生了一次资源竞争。目的是使得优先级的差异表现得更明显。
注:本篇博客内容摘自《Java高并发程序设计》