File tree Expand file tree Collapse file tree
codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/thread Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package io .github .dunwu .javase .concurrent .thread ;
22
3- class ThreadDaemon implements Runnable { // 实现Runnable接口
4- @ Override
5- public void run () {
6- while (true ) {
7- System .out .println (Thread .currentThread ().getName () + "在运行。" );
8- }
9- }
10- };
11-
3+ /**
4+ * 守护线程示例
5+ * 什么是守护线程
6+ * 守护线程(Daemon Thread)是在后台执行并且不会阻止 JVM 终止的线程。 与守护线程(Daemon Thread)相反的,叫用户线程(User
7+ * Thread),也就是非守护线程。
8+ * 为什么要用守护线程
9+ * 守护线程的优先级比较低,用于为系统中的其它对象和线程提供服务。典型的应用就是垃圾回收器。
10+ * 如何创建守护线程
11+ * 使用 thread.setDaemon(true) 可以设置 thread 线程为守护线程。
12+ * 注意点:
13+ * 正在运行的用户线程无法设置为守护线程,所以 thread.setDaemon(true)必须在 thread.start()之前设置,否则会抛出
14+ * llegalThreadStateException 异常; 一个守护线程创建的子线程依然是守护线程。 不要认为所有的应用都可以分配给 Daemon 来进行服务,比如读写操作或者计算逻辑。
15+ * @author Zhang Peng
16+ * @date 2018/1/18
17+ */
18+ public class ThreadDaemonDemo {
1219
20+ static class ThreadDaemon implements Runnable {
1321
22+ @ Override
23+ public void run () {
24+ while (true ) {
25+ System .out .println (Thread .currentThread ().getName () + "在运行。" );
26+ }
27+ }
28+ }
1429
15- public class ThreadDaemonDemo {
1630 public static void main (String [] args ) {
1731 ThreadDaemon mt = new ThreadDaemon (); // 实例化Runnable子类对象
1832 Thread t = new Thread (mt , "线程" ); // 实例化Thread对象
1933 t .setDaemon (true ); // 此线程在后台运行
34+ System .out .println ("线程 t 是否是守护进程:" + t .isDaemon ());
2035 t .start (); // 启动线程
2136 }
22- };
37+ }
You can’t perform that action at this time.
0 commit comments