【Java基础】Thread setDaemon 方法

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;
	}

	@Override
	public 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 block
				e.printStackTrace();
			}
		}
	}

}

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

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





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值