线程优先级
每个线程都有各自的优先级,线程的优先级可以表明在程序中该线程的重要性,如果有很多线程处于就绪状态,系统则会根据优先级来决定首先使哪个线程进入运行状态。但是这并不是意味着低优先级的线程得不到运行,而只是它运行的几率比较小,而高优先级的线程的运行几率比较高。
Thread类中包含的静态变量代表了线程的某些优先级,其中MIN_PRIORITY表示最低优先级1,NORM_PRIORITY表示中等优先级5,MAX_PRIORITY表示最高优先级10。
每个线程的的优先级都在MIN_PRIORITY到MAX_PRIORITY之间,在默认的情况下其优先级都是NORM_PRIORITY。并且每个新产生的线程都继承了父线程的优先级。
每当线程调度器有机会选择新线程时,它首先选择具有较高优先级的线程。但是,线程优先级是高度依赖于操作系统的。
当JVM依赖于宿主机系统的线程实现机制时,Java线程的优先级被映射到宿主机平台的优先级上,优先级个数也许更多,也许更少。
注意:不要将程序构建为功能的正确性依赖于线程的优先级
例如:
public class Test {
static int i = 0;
static class MyThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread(),"Thread1");
Thread thread2 = new Thread(new MyThread(),"Thread1");
Thread thread3 = new Thread(new MyThread(),"Thread1");
Thread thread4 = new Thread(new MyThread(),"Thread1");
Thread thread5 = new Thread(new MyThread(),"Thread1");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread3.setPriority(Thread.NORM_PRIORITY);
thread4.setPriority(Thread.MIN_PRIORITY);
thread5.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
运行结果:
从两次不同的运行结果看到,并不是意味着低优先级的线程得不到运行,而只是它运行的几率比较小,而高优先级的线程的运行几率比较高。
守护线程
我们可以通过setDeamon(true)方法将一个线程转换为守护线程。守护线程的唯一用途就是为其他线程服务。当程序中只剩下守护线程时,虚拟机就会退出,比如我们的垃圾回收线程就是守护线程。
我们创建的线程默认都是用户线程,虚拟机会等待所有用户线程运行完毕才会退出。
注意:守护线程应该永远不去访问固有资源,如文件、数据库,因为它会在任何时候甚至在一个操作的中间发生中断。