java守护线程作用-java线程解释器
发布时间:2023-05-31 22:13 浏览次数:次 作者:佚名
1)Java中的用户线程
我们可以使用setDaemon(boolean)方法将用户线程作为守护程序线程。例如:在此示例中,我们通过使用isDaemon()方法返回true来检查线程类型(用户线程或守护程序)java守护线程作用java守护线程作用,这意味着线程是守护程序,否则线程是非守护程序或用户。
class ChildThread extends Thread{ public void run(){ System.out.println("I am in ChildThread"); } } class ParentThread{ public static void main(String[] args){ ChildThread ct = new ChildThread(); ct.start(); System.out.println("I am in main thread"); System.out.println("Type of ChildThread: return true : Daemon and return false : Non-daemon " + " " + ct.isDaemon()); System.out.println("Type of ParentThread: return true : Daemon and return false : Non-daemon " + " " + Thread.currentThread().isDaemon()); } }
输出结果
D:\Java Articles>java ParentThread I am in main thread Type of ChildThread: return true : Daemon and return false : Non-daemon false Type of ParentThread: return true : Daemon and return false : Non-daemon false I am in ChildThread
2)Java中的守护进程线程
示例
在此示例中,我们使用setDeamon(布尔值)将非守护程序线程作为守护程序,但是我们无法更改主线程的行为。
class ChildThread extends Thread{ public void run(){ System.out.println("child thread is a non-daemon thread"); } } class MainThread{ public static void main(String[] args){ ChildThread ct = new ChildThread(); System.out.println("Before using setDaemon() method "+ " " + ct.isDaemon()); ct.setDaemon(true); System.out.println("After using setDaemon() method "+ " " + ct.isDaemon()); } }
输出结果
D:\Java Articles>java MainThread Before using setDaemon() method false After using setDaemon() method true