参考redis实现分布式锁的方式,使用看门狗的方式来执行具体任务
看门狗线程一般不是工作线程,而是监控线程,
但是我们需要执行的任务应该在子线程执行,而主线程应该等待子线程执行结果,
因此,使用看门狗线程执行具体任务,主线程循环轮询,是否子线程返回结果;
具体实现如下:
package com.test;
import java.util.Arrays;
import java.util.function.Function;
/**
* @author yangguang
* @date 2023年05月12日 13:52
*/
public class Test {
private int timeout;
private Function<String[],Integer> taskFunction;
private Thread taskThread;
private volatile Thread currentThread;
private String[] param;
private volatile Integer result;
public Test(int timeout,String[] param,Function<String[],Integer> taskFunction) {
this.timeout = timeout;
this.taskFunction = taskFunction;
this.param = param;
this.currentThread = Thread.currentThread();
}
public Integer startTask() {
taskThread = new Thread(()->{
result = taskFunction.apply(param);
currentThread.interrupt();
});
taskThread.start();
while (true) {
try {
Thread.sleep(timeout);
System.out.println("第三方接口调用超时");
taskThread.stop();
return -1;
} catch (InterruptedException e) {
System.out.println("第三方接口调用正常返回");
return result;
}
}
}
private static Function<String[],Integer> apiService(){
return param->{
try {
//调用第三方接口
System.out.println("接口参数为"+ Arrays.toString(param));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return 1;
};
}
public static void main(String[] args) {
Test test = new Test(3000,new String[]{"参数1","参数2"},apiService());
Integer r = test.startTask();
System.out.println("第三方接口返回结果为"+r);
test = new Test(1000,new String[]{"参数1","参数2"},apiService());
r = test.startTask();
System.out.println("第三方接口返回结果为"+r);
}
}