首先继承 Runnable Future 接口然后实现 我们只需要 用到run() 和get()方法就可以其它不用看 this.wait(); 调用这个方法让它阻塞,一致等到结果 然后调用notifyAll() 唤醒线程. import java.util.concurrent.*; public class JxdFutureTask<V> implements Runnable, Future<V> { Callable<V> callable; V result = null; //构造方法 public JxdFutureTask(Callable<V> callable) { this.callable = callable; } @Override public void run() { try { result =this.callable.call(); synchronized (this){ this.notifyAll();//唤醒阻塞等待的线程 } } catch (Exception e) { e.printStackTrace(); } } //需要实现,跑业务 @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return false; } @Override public V get() throws InterruptedException, ExecutionException { return null; } /** * 处理返回结果 */ @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (null != result) { return result; } //否则的话让它阻塞等待结果 synchronized (this){ this.wait(); } //执行到这里标识被唤醒 ,被唤醒意味着有值了 return result; } }
来源:https://blog.csdn.net/weixin_39831786/article/details/98865483