多线程基础知识总结(六)

时间:2023-01-21 17:31:05

全文概要

本文主要介绍线程的优先级和守护线程。

  • 创建的线程默认的优先级是5,当然可以自行设置优先级,优先级为[1,10]区间的整数
  • java中有两种线程,用户线程和守护线程,可以通过isDaemon()来判断,返回true表示守护线程;
  • 用户线程一般用来执行用户级任务,而守护线程一般用来执行后台任务,除此之外,守护线程有一个重要的特性:当所有的用户线程全部执行完毕后,无论守护线程的逻辑是否完成,JVM会自动结束守护线程。

守护线程介绍

  • 代码案例
package com.tml.javaCore.thread;

public class DaemoDemo {
	public static void main(String[] args) {
		
		Thread thread_01 = new Thread(new  Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName() + 
						":priority is:" + Thread.currentThread().getPriority() );
				for(int i=0;i<10;i++){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ": is loop " + i);
				}
			}
		}, "thread_01");
		thread_01.setPriority(1);
		thread_01.start();
		
		
		Thread thread_02 = new Thread(new  Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName() + 
						":priority is:" + Thread.currentThread().getPriority() );
				for(int i=0;i<100;i++){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + ": is loop " + i);
				}
			}
		}, "thread_02");
		thread_02.setDaemon(true);//设置守护线程一定要在start()方法之前
		thread_02.setPriority(10);
		thread_02.start();
	}

}

  • 输出结果

    thread_01:priority is:1
    thread_02:priority is:10
    thread_01: is loop 0
    thread_02: is loop 0
    thread_01: is loop 1
    thread_02: is loop 1
    thread_02: is loop 2
    thread_01: is loop 2
    thread_02: is loop 3
    thread_01: is loop 3
    thread_02: is loop 4
    thread_01: is loop 4
    thread_01: is loop 5
    thread_02: is loop 5
    thread_01: is loop 6
    thread_02: is loop 6
    thread_01: is loop 7
    thread_02: is loop 7
    thread_01: is loop 8
    thread_02: is loop 8
    thread_01: is loop 9

    thread_02: is loop 9

  • 结果分析

  1. 主线程中创建了连个线程,线程1的优先级设置为1,线程2的优先级设置为10,当设置线程优先级的值不在[1,10]整数区间内,会抛出java.lang.IllegalArgumentException运行时异常,除此之外,线程2还被设置为守护线程,注意设置守护线程一定要在start()方法之前,否则会抛出java.lang.IllegalThreadStateException运行时异常;
  2. 由于打印的时候,线程睡眠100毫秒,这就导致线程1和线程2依次执行打印任务;
  3. 线程1是用户线程,线程2是守护线程,当线程1执行完成后,JVM会自动结束线程2,即便线程2循环没有结束。