标签: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; } }
标签:rri his null ide str done [] lse thread
原文地址:https://www.cnblogs.com/junjie2019/p/10605514.html