Java 学习笔记之 Daemon线程

mac2022-06-30  63

Daemon线程:

 

线程:

用户线程守护线程

守护线程是一种特殊的线程,在进程中不存在非守护线程了,则守护线程自动销毁。

public class DaemonThread extends Thread { private int i = 0; @Override public void run() { try { while (true) { i++; System.out.println("i=" + (i)); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadRunMain { public static void main(String[] args) { testDaemonThread(); } public static void testDaemonThread() { try { DaemonThread dt = new DaemonThread(); dt.setDaemon(true); dt.start(); Thread.sleep(5000); System.out.println("Main thread disappear. Daemon thread will also disappear."); } catch (InterruptedException e) { e.printStackTrace(); } } }

运行结果:

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7705214.html

最新回复(0)