【Java基础】Thread setDaemon 方法

来源:互联网 发布:上瘾网络剧秒拍视频 编辑:程序博客网 时间:2024/04/29 15:28

Java基础,有的时候,你真的熟悉吗?

惭愧,很多基础真的没有细细看过,今后要多多看,细细学,勤笔记。


关于设置用户线程

void java.lang.Thread.setDaemon(boolean on)

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machineexits when the only threads running are all daemon threads.

This method must be called before the thread is started.

This method first calls the checkAccess method of this thread with no arguments. This may result in throwing aSecurityException(in the current thread).

Parameters:
on if true, marks this thread as a daemon thread.
Throws:
IllegalThreadStateException - if this thread is active.
SecurityException - if the current thread cannot modify this thread.
See Also:
isDaemon()
checkAccess

这里的描述:设置该线程为用户线程(Daemon原义:守护,其实这个意思不好理解)。用户线程的意义在于,在JVM里面,当只有Daemon线程时,JVM会停止(exit)。

另外,调用该方法必须在Thread.start 前进行。

应用场景:

    一般我们启动一个线程后,会在 run方法里面,while(true),即一直运行,有可能是在处理某些后台清理操作。它什么时候退出呢?当JVM终止时,退出。

    JVM什么时候退出呢?JVM只要有线程在运行时,就不会终止。这就产生了相互依赖的矛盾。


   当我们设置后台运行的线程为Daemon,并规定,当没有非Daemon线程时,JVM自动终止。这个矛盾就解决了!


代码解释:

     

package com.wateray.java.thread;public class DaemonTest {/** * @param args */public static void main(String[] args) {Thread thA = new Thread(new Task("TaskA", 1000));Thread thB = new Thread(new Task("TaskB", 1500));// thA.setDaemon(true);// thB.setDaemon(true);System.out.println("Start Thread thA, thB..");thA.start();thB.start();System.out.println("End main!");}}class Task implements Runnable {private String name;private long sleep;public Task(String name, long sleep) {this.name = name;this.sleep = sleep;}@Overridepublic void run() {while (true) {try {System.out.format("%s will sleep %d milliseconds %n", name,sleep);Thread.sleep(sleep);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

// thA.setDaemon(true);// thB.setDaemon(true);

如果这两行,去注释一个,JVM不会退出,如果两个都放开,则JVM会自动终止。因为主线程已经结束,只有用户进程了,这JVM自动终止。





0 0