ScheduledExecutorService 在shutdownNow 后停止可运行

问题描述

当我关闭 scheduledexecutorservice 时,我需要一些帮助来停止我当前的可运行线程。在下面的代码中,我想在终止父执行程序时停止我的流作业。

即使我使用了 shutdownNow() 它也不会停止当前正在运行的线程及其流循环。如果使用 InterruptedException 在 DoSomeHardJob.adding() 中有 Thread.sleep(),我可以终止。

scheduledFuture.cancel(true);

我试过上面的方法不起作用。我还有其他选择可以尝试终止当前的工作吗?任何帮助/想法都非常有用。


import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThreadWork {
    
    public static void main(String[] args) throws InterruptedException {
        
        scheduledexecutorservice schExService = Executors.newScheduledThreadPool(0);
        
        int repeatMin = 2;
        
         
        ScheduledFuture<?> scheduledFuture = schExService.scheduleWithFixedDelay(new runconfiguraiton(),repeatMin,TimeUnit.SECONDS);
        
        Thread.sleep(3*1000);
        
        scheduledFuture.cancel(true);
        schExService.shutdownNow();
 
        
        Thread.sleep(1*1000);
        
        System.out.println("I am good there for fresh start");
        
    }

}

class runconfiguraiton implements  Runnable
{

    @Override
    public void run() {
        
        List<Integer> intList = Arrays.asList(10,5,60,45,100,50,232);
        
        
     
         try {
            intList.stream().map(i -> {
                try {
                     return DoSomeHardJob.adding(i);
                }  catch (Exception e) {
                    // Todo Auto-generated catch block
                    e.printstacktrace();
                    return 0;
                }
                
             }).collect(Collectors.toList());
        } catch (Exception e) {
            System.out.println("final exit");
            e.printstacktrace();
        }
        
    }
    
    static class DoSomeHardJob{
        public static int adding(int i) throws Exception {
            try {
                int result = 0;
                for (int j = 0; j < 999999999; j++) {
                    System.out.print(j);
                    result = result + j; 
                }
                
                return result;
            } 
            catch (Exception e) {
                e.printstacktrace();
                 throw new RuntimeException(e);
            }
            
        }
    }
    
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)