首页 > 系统相关 >Java thread.setDaemon使用示例代码 守护进程

Java thread.setDaemon使用示例代码 守护进程

时间:2023-02-26 17:02:22浏览次数:37  
标签:Java thread Thread 示例 setDaemon 线程 守护

这个例子写的非常不错,易于理解

下面是一个简单的Java示例代码,演示如何使用Thread.setDaemon()方法将线程设置为守护线程:

点击查看代码
package com.kaka.rili;

public class DaemonThreadExample {
    public static void main(String[] args) {
        Thread thread = new Thread(new WorkerThread());
        thread.setDaemon(true); // 将线程设置为守护线程
        thread.start();

        // 主线程代码
        System.out.println("Main thread is running");
        try {
            Thread.sleep(5000); // 主线程休眠5秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread is exiting");
    }
}

class WorkerThread implements Runnable {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000); // 线程休眠1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Worker thread is running");
        }
    }
}

在上面的示例代码中,创建了一个WorkerThread类,它实现了Runnable接口,并在run()方法中执行一个无限循环,在每次循环中打印一条消息。然后,在主线程中创建了一个Thread对象,并使用setDaemon()方法将该线程设置为守护线程。主线程休眠5秒后退出。

当主线程退出时,守护线程也会自动退出。因为守护线程一直在运行无限循环,所以在程序退出前可以看到它打印了多条消息。如果将线程设置为非守护线程,则该线程将一直运行,直到它完成或使用Thread.interrupt()方法中断它。

标签:Java,thread,Thread,示例,setDaemon,线程,守护
From: https://www.cnblogs.com/kaka-qiqi/p/17157026.html

相关文章