java中的线程有自己的优先级,优先级高的线程在竞争资源时会更有优势,当然这是一个概率性问题,如果运气不好,高优先级的线程可能也会抢占失败;
java中从1-10表示线程的优先级
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
数字越大,优先级越高,下面代码展示了优先级的作用;
package com.example.demo;
import org.junit.Test;
import com.example.demo.PriorityDemo.HightPriority;
import com.example.demo.PriorityDemo.LowPriority;
public class PriorityDemo {
public static class HightPriority extends Thread {
static int count = 0;
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;
public void run() {
while(true) {
synchronized (PriorityDemo.class) {
count++;
if (count > 10000000) {
System.out.println("LowPriority is complete");
break;
}
}
}
}
}
@Test
public void testPriority() {
HightPriority hightPriority = new HightPriority();
LowPriority lowPriority = new LowPriority();
hightPriority.setPriority(Thread.MAX_PRIORITY);
lowPriority.setPriority(Thread.MIN_PRIORITY);
lowPriority.start();
hightPriority.start();
}
}
打印结果
HightPriority is complete
LowPriority is complete
上述代码中HightPriority 设置优先级比较高,
大多数情况下会先打印出这段话