java setdaemon_Java Thread setDaemon()方法

Thread类的setDaemon()方法用于将线程标记为守护程序线程或用户线程。 它的生命依赖于用户线程,即当所有用户线程都消亡时,JVM会自动终止该线程。必须在线程启动之前调用它。

如果在声明线程后调用setDaemon()方法,则此方法将抛出IllegalThreadStateException。

语法

public final void setDaemon(boolean on)

参数

on - 如果为true,则将该线程标记为守护程序线程。

返回值

如果线程是守护进程线程,则此方法将返回true,否则返回false。

异常

IllegalThreadStateException:如果线程处于活动状态。

SecurityException:如果当前线程无法修改线程。

示例

public class JavaSetDaemonExp1 extends Thread

{

public void run()

{

//checking for daemon thread

if(Thread.currentThread().isDaemon())

{

System.out.println("daemon thread work");

}

else

{

System.out.println("user thread work");

}

}

public static void main(String[] args)

{

// creating three threads

JavaSetDaemonExp1 t1=new JavaSetDaemonExp1();

JavaSetDaemonExp1 t2=new JavaSetDaemonExp1();

JavaSetDaemonExp1 t3=new JavaSetDaemonExp1();

// set user thread t1 to daemon thread

t1.setDaemon(true);

//call run() method

t1.start();

// set user thread t2 to daemon thread

t2.setDaemon(true);

// start of threads

t2.start();

t3.start();

}

}

执行上面示例代码,得到以下结果:

daemon thread work

daemon thread work

user thread work

示例二

在线程启动后调用setDaemon()方法时。

public class JavaSetDaemonExp2 extends Thread

{

public void run()

{

System.out.println("Name of thread: "+Thread.currentThread().getName());

// //checking for daemon thread

System.out.println("Daemon: "+Thread.currentThread().isDaemon());

}

public static void main(String[] args)

{

// creating two threads

JavaSetDaemonExp2 t1=new JavaSetDaemonExp2();

JavaSetDaemonExp2 t2=new JavaSetDaemonExp2();

// call run() method

t1.start();

// this will throw exception here

t1.setDaemon(true);

// call run() method

t2.start();

}

}

执行上面示例代码,得到以下结果:

Name of thread: Thread-0

Daemon: false

Exception in thread "main" java.lang.IllegalThreadStateException

at java.lang.Thread.setDaemon(Thread.java:1359)

at JavaSetDaemonExp2.main(JavaSetDaemonExp2.java:17)

¥ 我要打赏

纠错/补充

收藏

下一篇:哥,这回真没有了

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值