java 线程中止结合续期思想的小demo


    private volatile boolean isEnd = false;

    private Thread slaveThread;

    @GetMapping("/testThread")
    public AjaxResult testThread() {
        isEnd = false;
        Thread thread = Thread.currentThread();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!isEnd && !Thread.currentThread().isInterrupted()){
                    System.out.println("续费~~");
                    slaveThread = Thread.currentThread();
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        // 在子线程sleep的时候,主线程调用slaveThread.interrupt();会使子线程抛出异常 sleep InterruptedException 所以需要再次中断
                        slaveThread.interrupt();
                    }
                }
            }
        }).start();

        for (int i = 0; i < 5; i++) {
            try {
                System.out.println("主线程~~");
                thread.sleep(2000);
                if (i == 4 && slaveThread != null){
                    if (slaveThread.isAlive()){
                        slaveThread.interrupt();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("主线程结束");
        return null;
    }

你可能感兴趣的:(java)