本文共 1167 字,大约阅读时间需要 3 分钟。
非守护线程好理解,就是程序中前端运行的线程,我个人理解为常用于处理主动事务的线程。
守护线程:顾名思义,用来守护处理事务的线程。它主要运行在程序后端,最有代表的例子GC线程,就是守护线程。/** * Created by 一只会飞的猪 on 2021/3/8. */// 守护线程public class DaemonThread implements Runnable{ @Override public void run() { for (int i = 0; i <100000; i++) { System.out.println(Thread.currentThread().getName()+"我是守护线程,我正在运行"); } }}// 非守护线程class OtherThread implements Runnable{ @Override public void run() { for (int i = 0; i <10; i++) { System.out.println(Thread.currentThread().getName()+"我是非守护线程,我正在运行"); } }}class StartMain{ public static void main(String[] args) { // 启动非守护线程 new Thread(new OtherThread()).start(); // 设置守护线程 Thread threaddaomon = new Thread(new DaemonThread()); threaddaomon.setDaemon(true); // 启动线程 threaddaomon.start(); }
结果:
可以看出来,虽然我守护线程操作了100000次,但是在非守护线程结束后,守护线程并没有继续执行。转载地址:http://cjhof.baihongyu.com/