package example.thread.future;
public interface IFuture<R> {
public R get() throws InterruptedException;
public void set(R r);
}
package example.thread.future.impl;
import example.thread.future.IFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class SimpleFuture<R> implements IFuture<R> {
private R result;
/** 标识future是否完成*/
private volatile boolean finish = false;
private ReentrantLock reentrantLock = new ReentrantLock();
private Condition condition = reentrantLock.newCondition();
@Override
public R get() throws InterruptedException {
try{
reentrantLock.lock();
if (!finish){
condition.await();
}
}finally {
reentrantLock.unlock();
}
return result;
}
@Override
public void set(R r) {
if (!finish){
try{
reentrantLock.lock();
if (!finish){
finish = true;
this.result = r;
condition.signalAll();
}
} finally {
reentrantLock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
IFuture<Integer> future = new SimpleFuture<>();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(2);
future.set(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println(future.get());
}
}