码迷,mamicode.com
首页 > 其他好文 > 详细

Future设计模式

时间:2019-03-27 10:47:03      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:rri   his   null   ide   str   done   []   lse   thread   

import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String[] args){

    }
}

interface Future<T>{
    T get() throws InterruptedException;
    boolean done();
}

interface Task<IN, OUT>{
    OUT get(IN input);
}

interface FutureService<IN,OUT>{
    Future<?> submit(Runnable runnable);
    Future<OUT> submit(Task<IN,OUT> task,IN input);
}

class FutureTask<T> implements Future<T>{
    private T result;
    private boolean isDone = false;
    private final Object LOCK = new Object();

    @Override
    public T get() throws InterruptedException {
        synchronized (LOCK){
            while (!isDone) {
                LOCK.wait();
            }
            return result;
        }
    }

    protected void finish(T result) {
        synchronized (LOCK) {
            if (isDone) {
                return;
            }

            this.result=result;
            this.isDone=true;
            LOCK.notifyAll();
        }
    }

    @Override
    public boolean done() {
        return isDone;
    }
}

class FutureServiceImpl<IN,OUT> implements FutureService<IN,OUT>{

    private final static String FUTURE_PREFIX = "FUTURE-";
    private final AtomicInteger nextCounter = new AtomicInteger(0);

    private String getNextName(){
        return FUTURE_PREFIX+nextCounter.getAndIncrement();
    }

    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Void> future = new FutureTask<>();
        new Thread(()->{
            runnable.run();
            future.finish(null);
        },getNextName()).start();
        return future;
    }

    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(()->{
            OUT result = task.get(input);
            future.finish(result);
        },getNextName()).start();
        return future;
    }
}

 

Future设计模式

标签:rri   his   null   ide   str   done   []   lse   thread   

原文地址:https://www.cnblogs.com/junjie2019/p/10605514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!