一、线程的优先级
1.Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
2.线程的优先级用数字表示,范围从1~10.
Thread.MIN_PRIORITY = 1;
Thread.NORM_PRIORITY = 5;
Thread.MAX_PRIORITY = 10;
3.使用以下方式改变或者获取优先级
getPriority();
setPriority(int newPriority);
代码如下:
public class PriorityThreadTest implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());//打印main线程优先级 PriorityThreadTest priorityThreadTest = new PriorityThreadTest(); Thread t0 = new Thread(priorityThreadTest); t0.start(); Thread t1 = new Thread(priorityThreadTest); t1.setPriority(Thread.MIN_PRIORITY); t1.start(); Thread t2 = new Thread(priorityThreadTest); t2.setPriority(3); Thread t3 = new Thread(priorityThreadTest); t3.setPriority(3); t3.start(); Thread t4 = new Thread(priorityThreadTest); t4.setPriority(4); t4.start(); Thread t5 = new Thread(priorityThreadTest); t5.setPriority(Thread.NORM_PRIORITY); t5.start(); Thread t6 = new Thread(priorityThreadTest); t6.setPriority(6); t6.start(); Thread t7 = new Thread(priorityThreadTest); t7.setPriority(7); t7.start(); Thread t8 = new Thread(priorityThreadTest); t8.setPriority(8); t8.start(); Thread t9 = new Thread(priorityThreadTest); t9.setPriority(9); t9.start(); Thread t10 = new Thread(priorityThreadTest); t10.setPriority(Thread.MAX_PRIORITY); t10.start(); } }
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
二、守护(daemon)线程
1.线程分为用户线程(main)和守护线程(gc)。
2.虚拟机必须确保用户线程执行完毕。
3.虚拟机不用等待守护线程执行完毕。
4.thread.setDaemon(true);正常的线程都是用户线程,除非你添加了守护线程。