package com.lms.jdk8.juc;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;/** * @Author: 李孟帅 * @Date: 2021-12-14 15:14 * @Description: */@Slf4jpublic class FutureResult { private Object result; public Object get() throws InterruptedException { synchronized (this) { while (result == null) { this.wait(); } return result; } } public Object get(long timeout) throws InterruptedException { synchronized (this) { long begin = System.currentTimeMillis(); long duration = 0; while (result == null) { long waitTime = timeout - duration; if (waitTime <= 0) { break; } this.wait(waitTime); duration = System.currentTimeMillis() - begin; } return result; } } public void complete(Object result) { synchronized (this) { this.result = result; this.notifyAll(); } } public static void main(String[] args) { FutureResult futureResult = new FutureResult(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { log.info("等待结果。。"); Object o = futureResult.get(2000); log.info("结果:{}",o); } },"t1").start(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { log.info("下载。。。"); Thread.sleep(5000); futureResult.complete(111); } },"t2").start(); }}