java获取异步线程执行结果示例,也是Executors框架的基本原理
人狠话不多,直接上代码,代码拷贝到本地直接运行,自己研究吧。
public interface MyFuture<V> { V get() throws Exception; }
public interface Callback<v> { v call() throws Exception; }
public class ExecuteThread<V> extends Thread { private V result=null; private Exception exception=null; private boolean done=false; private Callback<V> task; private Object lock; public ExecuteThread(Callback<V> task, Object lock) { this.task = task; this.lock = lock; } @Override public void run() { try { result=task.call(); } catch (Exception e) { //e.printStackTrace(); exception=e; }finally { synchronized (lock){ done=true; lock.notifyAll(); } } } public V getResult() { return result; } public Exception getException() { return exception; } public boolean isDone() { return done; } }
public class MyExecutor<V> { public <V> MyFuture<V> execute(final Callback<V> task){ final Object lock=new Object(); final ExecuteThread<V> thread=new ExecuteThread<>(task,lock); thread.start(); MyFuture<V> future=new MyFuture<V>() { @Override public V get() throws Exception { synchronized (lock){ while (!thread.isDone()){ lock.wait(); } } if(thread.getException()!=null){ throw thread.getException(); } return thread.getResult(); } }; return future; } }
主线程代码:
import java.util.Random; public class Main { public static void main(String[] args) throws Exception { MyExecutor executor=new MyExecutor(); Callback<Integer> subTask=new Callback<Integer>() { @Override public Integer call() throws Exception { Random rdm=new Random(); int millis=rdm.nextInt(1000); Thread.sleep(millis); return millis; } }; MyFuture<Integer> future=executor.execute(subTask); Integer result=future.get(); System.out.println(result); } }
代码枯燥难懂,但是我有什么办法呢?
只能自己慢慢研究了。