1. package com.lms.jdk8.juc;
    2. import lombok.SneakyThrows;
    3. import lombok.extern.slf4j.Slf4j;
    4. /**
    5. * @Author: 李孟帅
    6. * @Date: 2021-12-14 15:14
    7. * @Description:
    8. */
    9. @Slf4j
    10. public class FutureResult {
    11. private Object result;
    12. public Object get() throws InterruptedException {
    13. synchronized (this) {
    14. while (result == null) {
    15. this.wait();
    16. }
    17. return result;
    18. }
    19. }
    20. public Object get(long timeout) throws InterruptedException {
    21. synchronized (this) {
    22. long begin = System.currentTimeMillis();
    23. long duration = 0;
    24. while (result == null) {
    25. long waitTime = timeout - duration;
    26. if (waitTime <= 0) {
    27. break;
    28. }
    29. this.wait(waitTime);
    30. duration = System.currentTimeMillis() - begin;
    31. }
    32. return result;
    33. }
    34. }
    35. public void complete(Object result) {
    36. synchronized (this) {
    37. this.result = result;
    38. this.notifyAll();
    39. }
    40. }
    41. public static void main(String[] args) {
    42. FutureResult futureResult = new FutureResult();
    43. new Thread(new Runnable() {
    44. @SneakyThrows
    45. @Override
    46. public void run() {
    47. log.info("等待结果。。");
    48. Object o = futureResult.get(2000);
    49. log.info("结果:{}",o);
    50. }
    51. },"t1").start();
    52. new Thread(new Runnable() {
    53. @SneakyThrows
    54. @Override
    55. public void run() {
    56. log.info("下载。。。");
    57. Thread.sleep(5000);
    58. futureResult.complete(111);
    59. }
    60. },"t2").start();
    61. }
    62. }