线程的定时任务类ScheduledExecutorService

线程的定时任务类ScheduledExecutorService

前言

最近再看dubbo源码的时候(DubboRegistry),有这么一段

// 定时任务执行器
private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true));

// 重连定时器,定时检查连接是否可用,不可用时,无限次重连
private final ScheduledFuture reconnectFuture;

/..../

public DubboRegistry(Invoker registryInvoker, RegistryService registryService) {
        super(registryInvoker.getUrl());
        this.registryInvoker = registryInvoker;
        this.registryService = registryService;
        // 启动重连定时器
        int reconnectPeriod = registryInvoker.getUrl().getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT);
        reconnectFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                // 检测并连接注册中心
                try {
                    connect();
                } catch (Throwable t) { // 防御性容错
                    logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t);
                }
            }
        }, reconnectPeriod, reconnectPeriod, TimeUnit.MILLISECONDS);
    }

实现的功能,当终端与注册中心断开连接时要自动检测并实现重连的功能。
查看ScheduledExecutorService源码:是在给定的延迟时间后,或者周期性执行的一个任务命令。

* An {@link ExecutorService} that can schedule commands to run after a given
 * delay, or to execute periodically.
 *
 * 

The schedule methods create tasks with various delays * and return a task object that can be used to cancel or check * execution. The scheduleAtFixedRate and * scheduleWithFixedDelay methods create and execute tasks * that run periodically until cancelled.

在看ScheduledExecutorService创建方式:

private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true));

NamedThreadFactory中的构造方法:

public NamedThreadFactory(String prefix,boolean daemo)
	{
		mPrefix = prefix + "-thread-";
		mDaemo = daemo;
        SecurityManager s = System.getSecurityManager();
        mGroup = ( s == null ) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
	}
@Override
public Thread newThread(Runnable runnable)
{
	String name = mPrefix + mThreadNum.getAndIncrement();
    Thread ret = new Thread(mGroup,runnable,name,0);
    ret.setDaemon(mDaemo);
    return ret;
}

在这里引出了本文主要说明的ret.setDaemon(mDaemo); 守护进程

一、守护进程和线程

守护进程(daemon)是一类在后台运行的特殊进程,用于执行特定的系统任务。很多守护进程在系统引导的时候启动,并且一直运行直到系统关闭。另一些只在需要的时候才启动,完成任务后就自动结束。源自百度百科

在Java中,守护线程(Daemon Thread)是指

示例demo:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.alibaba.dubbo.common.utils.NamedThreadFactory;

public class ScheduledExecutorTest {
	private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true));
	public void test(){
		
		this.scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("监测,,,,,,,,,,");
				System.out.println("scheduledExecutor"+"=============="+System.currentTimeMillis());
			}
		}, 3000, 3000, TimeUnit.MILLISECONDS);
		
	}
	
	public static void main(String[] args) {
		ScheduledExecutorTest test = new ScheduledExecutorTest();
		test.test();
		
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				int i = 0;
				while (i< 100) {
					System.out.println("+++++++++++++++" + i);
					
					try {
						Thread.sleep(30000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					i++;
				}
			}
		});
		thread.start();
	}
}

当用户线程执行完毕以后,守护线程立刻结束。

你可能感兴趣的:(Java)