简介:
此demo说明,当2个线程请求同一把锁谁先执行谁后执行,只需设置优先级即可。
既是setPriority(Thread.MAX_PRIORITY);的设置,而不管是谁先start。
demo示例:
/**
* @author T.c
* 创建时间:2016年11月4日 下午21:13:57
*
*/
public class PriorityDemo {
public static class HighPriority extends Thread {
static int count = 0;
public void run() {
while (true) {
synchronized (PriorityDemo.class) { // 请求同一把锁
count++;
if (count > 10000000) {
System.out.println("HightPrority is complete...");
break;
}
}
}
}
}
public static class LowPrority extends Thread {
static int count = 0;
public void run(){
while(true){
synchronized (PriorityDemo.class) {
count ++;
if(count > 10000000){
System.out.println("LowPrority is complete...");
break;
}
}
}
}
}
public static void main(String[] args) {
Thread highPriority = new HighPriority();
Thread lowPrority = new LowPrority();
highPriority.setPriority(Thread.MAX_PRIORITY);
lowPrority.setPriority(Thread.MIN_PRIORITY);
lowPrority.start();
highPriority.start();
}
运行结果:
HightPrority is complete...
LowPrority is complete...