package com.examlple;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;

public class FutureTest {

    public static void main(String[] args) throws InterruptedException {
        var beginTime = System.currentTimeMillis();
        final AtomicBoolean isBegin = new AtomicBoolean(false);
        final AtomicBoolean isEnd = new AtomicBoolean(false);
        Future<String> futureTask = ThreadUtil.execAsync(() -> {
            Thread.sleep(3 * 1000);
            isBegin.set(true);
            Thread.sleep(7 * 1000);
            isEnd.set(true);
            return "res";
        });

        // 等待 begin，超时时间20秒
        while (true) {
            Thread.sleep(1000);
            System.out.println("isBegin: " + isBegin.get() + " | isEnd: " + isEnd);

            if (!isBegin.get()) {
                if ((System.currentTimeMillis() - beginTime) > 20 * 1000) {
                    futureTask.cancel(true);
                    break;
                }
            } else {
                break;
            }
        }
        // 如果等待到 begin，开始等待 end，重置开始时间，超时时间60秒，否则跳过
        if (isBegin.get()) {
            beginTime = System.currentTimeMillis();
            while (true) {
                Thread.sleep(1000);
                System.out.println("isBegin: " + isBegin.get() + " | isEnd: " + isEnd);

                if (!isEnd.get()) {
                    if ((System.currentTimeMillis() - beginTime) > 60 * 1000) {
                        futureTask.cancel(true);
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        System.out.println("最终输出 isBegin: " + isBegin.get() + " | isEnd: " + isEnd);

        // Future 也可以使用 get方法 指定超时时间，对于简答的任务超时控制可以直接用这种方式
        /*
        try {
            String res = futureTask.get(4, TimeUnit.SECONDS);
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("中断异常");
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("执行异常");
        } catch (TimeoutException e) {
            e.printStackTrace();
            System.out.println("方法执行超时");
        }
        */
    }

}
