zoukankan      html  css  js  c++  java
  • java 关闭线程

    public class ThreadService {
    
        private Thread executeThread;
        private boolean finished = false;
    
        public void execute(Runnable task) {
            executeThread = new Thread() {
                @Override
                public void run() {
                    Thread runner = new Thread(task);
                    runner.setDaemon(true);
                    runner.start();
    
                    try {
                        runner.join();
                        finished = true;
                    } catch (InterruptedException e) {
                        System.out.println("intrupted   finished");
                        //  e.printStackTrace();
                    }
                }
            };
            executeThread.start();
        }
    
        public void shutdown(long mills) {
            long currentTime = System.currentTimeMillis();
            while (!finished) {
                long cost=(System.currentTimeMillis() - currentTime);
                System.out.println(cost);
                if (cost>= mills) {
                    System.out.println("timeout!!!");
                    executeThread.interrupt();
                    break;
                }
    
                try {
                    executeThread.sleep(1);
                } catch (InterruptedException e) {
                    System.out.println("execute is intrupeted");
                    break;
                }
    
            }
            finished=false;
        }
    }

    通过关闭主线程的方式让守护线程 自动关闭

    子线程再运行结束时通过join 通知主线程  说自己执行完了,通过结束中断主线程来让子线程自动退出,解决了 线程block   中无法结束的问题

    public class ThreadCloseForce {
        public static void main(String[] args) {
            ThreadService service=new ThreadService();
            long start=System.currentTimeMillis();
            service.execute(()->{
                //read data
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            service.shutdown(10000);
            long end=System.currentTimeMillis();
            System.out.println(end-start);
        }
    }
  • 相关阅读:
    gradle下载安安装教程
    mybatis 一对一association ,一对多collection
    Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleBuildError:
    API
    VUE 自定组件,注意事项,注意事件
    IDEA设置
    正则表达式
    前端页面适配的rem换算
    webpack打包原理
    vue-cli脚手架工具根目录的babelrc配置文件
  • 原文地址:https://www.cnblogs.com/BARAMONGAN/p/7436351.html
Copyright © 2011-2022 走看看