Java高并发学习(5)
先干重要的事:线程优先级
Java中的线程可以有优先级。优先级高的线程在竞争资源时更有优势。当然这只是一个概率问题。如果运气不好,高优先级的线程也可能抢占失败。
在java中使用1到10表示线程的优先级。一般用静态标量表示:
public final static int MIN_PRIORITY = 1;
public final static int MIN_PRIORITY = 1;
数字越大优先级越高,但有限范围在1到10之间。下面代码展示了优先级的作用。高优先级的线程倾向于更快的完成。
public class fist{
public final static int MIN_PRIORITY = 1;
public final static int MAX_PRIORITY = 10;
public static class MyThread_H extends Thread{
static int count = 0;
@Override
public void run(){
while(true){
synchronized (this) {
count++;
if(count>100000){
System.out.println("HightPriority is complete");
break;
}
}
}
}
}
public static class MyThread_L extends Thread{
static int count = 0;
@Override
public void run(){
while(true){
synchronized (this) {
count++;
if(count>100000){
System.out.println("LowPriority is complete");
break;
}
}
}
}
}
public static void main(String args[]) throws InterruptedException {
MyThread_H h = new MyThread_H();
MyThread_L l = new MyThread_L();
h.setPriority(MAX_PRIORITY);
l.setPriority(MIN_PRIORITY);
h.start();
l.start();
}
}
上述代码的两个线程,分别设置优先级为1和10,然后让他们完成相同的工作,也就是把count从0加到100000,完成后打印一个提示信息,这样就知道谁先完成了工作了。
这里要注意,在对count累加前,我们使用synchronized产生了一次资源竞争。目的是为了使优先级的差异表现的更明显。
大家尝试运行上诉的代码,可以看到,高优先级的线程在大部分情况下,都会首先完成任务,但不能保证所情况下都是这样。
---------------------