Future设计模式

Posted junjie2019

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Future设计模式相关的知识,希望对你有一定的参考价值。

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设计模式的主要内容,如果未能解决你的问题,请参考以下文章

多线程手写Future模式

多线程设计模式——Read-Write Lock模式和Future模式分析

Java 多线程中的Future

Future模式理解及FutureTask应用场景

Java深入学习:Future模式

多线程之Future模式