看门狗用于监听某个线程,当某个线程结束后,该监听程序也随之结束
该程序改进后可以再redis分布式锁超时续约时使用,防止锁时间固定时候不正当解锁时使用,看门狗负责续约,主程序结束不续约,则能保证锁时间不再无限续约
看门狗:
package com.test;
import java.lang.ref.WeakReference;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
/**
* *************************************************************************
* <p/>
*
* @文件名称: WatchDogManager.java
* @包 路 径: com.haerbin.sheng.test
* @版本: V1.0 @创建人:wocan23
* @创建时间:2020/9/29 17:12
*/
public class WatchDogManager {
private static ConcurrentHashMap<Long, WeakReference<Thread>> map= new ConcurrentHashMap();
static void watch(Thread thread){
map.put(thread.getId(),new WeakReference<>(thread));
}
static void start(){
new Thread(new Runnable() {
@Override
public void run() {
while (true){
Enumeration<Long> keys = map.keys();
while (keys.hasMoreElements()){
Long aLong = keys.nextElement();
WeakReference<Thread> threadWeakReference = map.get(aLong);
System.out.println(threadWeakReference.get());
if(threadWeakReference.get() != null){
System.out.println("thread:"+aLong+"监听");
}else{
map.remove(aLong);
System.out.println("thread:"+aLong+"不监听");
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
static class TestRunnable implements Runnable{
private String name;
private String desc;
public TestRunnable(String name, String desc) {
this.name = name;
this.desc = desc;
}
@Override
public void run() {
System.out.println(desc);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程"+name+"结束");
}
}
public static void main(String[] args) {
test();
int i = 10000;
while (i-->0){
System.gc();
}
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void test(){
Thread thread1 = new Thread(new TestRunnable("1", "no 111111"));
Thread thread2 = new Thread(new TestRunnable("2", "no 22222"));
Thread thread3 = new Thread(new TestRunnable("3", "no 33333"));
Thread thread4 = new Thread(new TestRunnable("4", "no 44444"));
Thread thread5 = new Thread(new TestRunnable("5", "no 55555"));
start();
watch(thread1);
watch(thread2);
watch(thread3);
watch(thread4);
watch(thread5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
输出结果:
no 111111
no 33333
no 22222
no 44444
no 55555
Thread[Thread-4,5,main]
线程1结束
线程2结束
线程3结束
thread:16监听
线程5结束
线程4结束
null
thread:12不监听
null
thread:13不监听
null
thread:14不监听
null
thread:15不监听
null
thread:16不监听