线程优先级,守护线程
1、线程优先级
Thread源码优先级定义1-10
/** * The minimum priority that a thread can have. */ public final static int MIN_PRIORITY = 1; /** * The default priority that is assigned to a thread. */ public final static int NORM_PRIORITY = 5; /** * The maximum priority that a thread can have. */ public final static int MAX_PRIORITY = 10;
调度器倾向于让优先级高的先执行,但是CPU处理线程的顺序是不确定的。优先级低的线程只是执行的频率较低。一般线程已默认优先级运行,试图操作优先级是一种错误
2、daemon(守护线程,后台线程)
程序在运行时在后台提供一种服务的线程。所有非守护线程结束时,程序终止,守护线程也终止。
/** * 守护线程测试类 * @author monkjavaer * @date 2018/11/22 22:54 */ public class DaemonsThread implements Runnable { @Override public void run() { try { while (true) { TimeUnit.MILLISECONDS.sleep(100); System.out.println("守护线程"+Thread.currentThread() + " " + this); } } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { for (int i=0;i<10;i++) { Thread thread = new Thread(new DaemonsThread()); thread.setDaemon(true); thread.start(); } System.out.println("main线程执行完==="); TimeUnit.MILLISECONDS.sleep(1000); } }