ScheduledExecutorService调度线程池运行几次后停止某一个线程
程序员文章站
2023-11-25 22:22:40
开发中偶尔会碰到一些轮询需求,比如我碰到的和银行对接,在做完某一个业务后银行没有同步给到结果,这时候就需要查询返回结果,我们的需求是5分钟一次,查询3次,3次过后如果没有结果则T+1等银行的文件,对于这种任务我们的要求是轮询不是很严格,所以我采取调度线程池方式,如果有查询任务,加入线程池,设置好执行 ......
开发中偶尔会碰到一些轮询需求,比如我碰到的和银行对接,在做完某一个业务后银行没有同步给到结果,这时候就需要查询返回结果,我们的需求是5分钟一次,查询3次,3次过后如果没有结果则t+1等银行的文件,对于这种任务我们的要求是轮询不是很严格,所以我采取调度线程池方式,如果有查询任务,加入线程池,设置好执行次数及执行时间间隔,具体代码如下:
1 import org.junit.test; 2 import org.slf4j.logger; 3 import org.slf4j.loggerfactory; 4 5 import java.util.concurrent.*; 6 7 8 public class localtest { 9 10 private static final logger log = loggerfactory.getlogger(localtest.class); 11 12 @test 13 public void test01() throws interruptedexception { 14 scheduledexecutorservice executorservice = executors.newscheduledthreadpool(1); 15 concurrenthashmap<string, future> futuremap = new concurrenthashmap<>(); 16 17 jobtest jobtest1 = new jobtest("job1",futuremap); 18 future future1 = executorservice.scheduleatfixedrate(jobtest1,1, 5, timeunit.seconds); 19 futuremap.put(jobtest1.getjobid(),future1); 20 21 jobtest jobtest2 = new jobtest("job2",futuremap); 22 future future2 = executorservice.scheduleatfixedrate(jobtest2,1, 5, timeunit.seconds); 23 futuremap.put(jobtest2.getjobid(),future2); 24 25 thread.sleep(1000l * 30); 26 27 jobtest jobtest3 = new jobtest("job3",futuremap); 28 future future3 = executorservice.scheduleatfixedrate(jobtest3,1, 5, timeunit.seconds); 29 futuremap.put(jobtest1.getjobid(),future3); 30 31 jobtest jobtest4 = new jobtest("job4",futuremap); 32 future future4 = executorservice.scheduleatfixedrate(jobtest4,1, 5, timeunit.seconds); 33 futuremap.put(jobtest4.getjobid(),future4); 34 35 thread.sleep(1000l * 300); 36 executorservice.shutdown(); 37 } 38 39 @test 40 public void test02() { 41 42 } 43 44 class jobtest implements runnable { 45 46 private concurrenthashmap<string, future> futuremap; 47 private int count = 0; 48 private string jobid; 49 50 public jobtest(){ 51 52 } 53 54 public jobtest(string jobid, concurrenthashmap<string, future> futuremap) { 55 super(); 56 this.jobid = jobid; 57 this.futuremap = futuremap; 58 } 59 60 @override 61 public void run() { 62 count++; 63 log.info("{} count is {}", jobid, count); 64 if (count > 2) { 65 future future = futuremap.remove(jobid); 66 future.cancel(true); 67 log.info("{} had cancel", jobid); 68 } 69 } 70 71 public string getjobid() { 72 return jobid; 73 } 74 75 public void setjobid(string jobid) { 76 this.jobid = jobid; 77 } 78 79 public concurrenthashmap<string, future> getfuturemap() { 80 return futuremap; 81 } 82 83 public void setfuturemap(concurrenthashmap<string, future> futuremap) { 84 this.futuremap = futuremap; 85 } 86 } 87 }
由于任务是放在队列,在内存里面,所以应用重启会导致任务丢失,如果对于严格要求轮询查询的不合适用这种方式