多线程实现强制停止替代过时的stop方法

最近学习汪文君的多线程时,看到一个强制停止线程的课程,觉得很有用就将其改良一下,便于以后备用

1.定义一个线程服务:

 

/**
 * @Author: MR LIS
 * @Description: 替代Thread.stop()方法的实现,通过main方法传入的task(实际任务),将其设置为守护线程
 * @Date: 14:36 2018/4/19
 * @return
 */
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();//runner线程join住的是执行线程
                    finished = true;
                } catch (InterruptedException e) {
//                    e.printStackTrace();
                    System.out.println("runner线程被打断");
                }
            }
        };

        executeThread.start();
    }

    public void shutdown(long mills) {
        long currentTime = System.currentTimeMillis();
        while (!finished) {
            //执行线程的守护线程任务未执行完成时,通过执行线程去打断runner线程,然后一个break,退出while循环
            if ((System.currentTimeMillis() - currentTime) >= mills) {
                System.out.println("任务超时,需要结束它!");
                executeThread.interrupt();
                break;
            }

            try {
                executeThread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("executeThread执行线程被打断!");
                break;
            }
        }

        finished = false;
    }
}

2.主方法调用:

 

/**
 * @Author: MR LIS
 * @Description:暴力停止线程,替代stop
 * @Date: 14:23 2018/4/19
 * @return
 */
public class ThreadCloseForce {

    /**
     * while (true) {

     }时,模拟演示的加载时间很长,超过等待时间,
     * @param args
     */

    /**
     * 超时等待时间,超过等待时间就强制结束
     */
    private static long waitTimeout = 10000;

    /**
     * 加载资源或执行任务可能会用到的时间,
     */
    private static long executeTime = 100000;



    public static void main(String[] args) {
        /***
         * executeTimewaitTimeout时,超时,修改finished状态为完成,强制退出
         *
         */
        ThreadService service = new ThreadService();
        long start = System.currentTimeMillis();
        service.execute(() -> {
            try {
                Thread.sleep(executeTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //10秒钟等待时间,如果资源没有加载完强制停止,通过finished状态来实现
        service.shutdown(waitTimeout);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}

 

你可能感兴趣的:(多线程)