线程优先级:
在JAVA线程中,通过一个int型变量priority来控制线程优先级,线程的有限机为1-10,默认为5,优先级高的线程获得的运行时间要高于优先级低的线程。但这只是一个提示,操作系统和JVM可能会根据自身情况忽略这个情况。请看下面代码:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit; public class Priority {
private static volatile boolean notStart=true;
private static volatile boolean notEnd=true; public static void main(String[] args) throws Exception{
List<Job> jobs=new ArrayList<>();
for(int i=0;i<10;++i){
int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;
Job job=new Job(priority);
jobs.add(job);
Thread thread=new Thread(job,"Thread"+i);
thread.setPriority(priority);
thread.start();
//thread.setPriority(188); 优先级超出1-10,这个范围时,运行期会抛异常;
}
notStart=false;
TimeUnit.SECONDS.sleep(10);
notEnd=false;
for(Job job:jobs){
System.out.println("Job Priority:"+job.priority+",Conut:"+job.jobCount);
} } private static class Job implements Runnable{
private int priority;
private long jobCount; public Job(int priority) {
this.priority = priority;
} public void run() {
while(notStart){
Thread.yield();
}
while (notEnd){
Thread.yield();
jobCount++;
}
}
}
执行结果如下:
Job Priority:1,Conut:4665639
Job Priority:1,Conut:4814788
Job Priority:1,Conut:4783102
Job Priority:1,Conut:5667441
Job Priority:1,Conut:4688465
Job Priority:10,Conut:4618501
Job Priority:10,Conut:5598076
Job Priority:10,Conut:5212791
Job Priority:10,Conut:5627112
Job Priority:10,Conut:4332899
线程状态: