模拟future

import java.util.concurrent.ExecutionException;

abstract public class MyFuture {

    private volatile Object returnVal;
    private volatile Boolean isException = false;
    private volatile ExecutionException exception;
    private Thread thread;

    public abstract Object call() throws Exception;

    public void start() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    returnVal = call();
                } catch (Exception e) {
                    exception = new ExecutionException(e);
                    isException = true;
                }
            }
        });
        thread.start();
    }

    public Object get() throws InterruptedException, ExecutionException {
        thread.join();
        if(isException)
            throw exception;
        return returnVal;
    }


    public static void main(String [] f) {

        Long st = System.currentTimeMillis();

        MyFuture myFuture = new MyFuture() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(5000);
                return 1;
            }
        };

        myFuture.start();

        try {
            Object ret = myFuture.get();
            System.out.println(ret);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println(System.currentTimeMillis() - st);

        MyFuture myFutureEx = new MyFuture() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(5000);
                int a = 1/0;
                return 1;
            }
        };

        myFutureEx.start();

        try {
            Object ret = myFutureEx.get();
            System.out.println(ret);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println(System.currentTimeMillis() - st);
    }
}

  

1
5010
10016
java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
at Thread.MyFuture$1.run(MyFuture.java:24)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ArithmeticException: / by zero
at Thread.MyFuture$3.call(MyFuture.java:69)
at Thread.MyFuture$1.run(MyFuture.java:22)
... 1 more

posted on 2020-04-10 14:18  silyvin  阅读(100)  评论(0编辑  收藏  举报