没有时间的限制

  1. package org.example.concurrency.test;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * @author huskyui
  6. */
  7. @Slf4j
  8. public class GuardedObject {
  9. private Object response;
  10. public Object get(){
  11. synchronized (this){
  12. while (response == null){
  13. try{
  14. this.wait();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. return response;
  20. }
  21. }
  22. public void complete(Object response){
  23. synchronized (this){
  24. this.response = response;
  25. this.notifyAll();
  26. }
  27. }
  28. public static void main(String[] args) {
  29. GuardedObject guardedObject = new GuardedObject();
  30. new Thread(()->{
  31. log.info("获取结果");
  32. String response = (String)guardedObject.get();
  33. log.info("结果{}",response);
  34. },"t1").start();
  35. new Thread(()->{
  36. log.info("执行任务");
  37. try {
  38. TimeUnit.SECONDS.sleep(2);
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. }
  42. guardedObject.complete(new String("hello"));
  43. },"t2").start();
  44. }
  45. }

可以看到线程1在等待线程二的任务结束,后现场一获取结果

设置时间的限制

  1. package org.example.concurrency.test;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * @author huskyui
  6. */
  7. @Slf4j
  8. public class GuardedObject {
  9. private Object response;
  10. public Object get() {
  11. synchronized (this) {
  12. while (response == null) {
  13. try {
  14. this.wait();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. return response;
  20. }
  21. }
  22. public Object get(long timeout) {
  23. long begin = System.currentTimeMillis();
  24. long passedTime = 0;
  25. synchronized (this) {
  26. while (response == null) {
  27. long delay = timeout - passedTime;
  28. if (delay <= 0) {
  29. break;
  30. }
  31. try {
  32. this.wait(delay);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. passedTime = System.currentTimeMillis() - begin;
  37. }
  38. return response;
  39. }
  40. }
  41. public void complete(Object response) {
  42. synchronized (this) {
  43. this.response = response;
  44. this.notifyAll();
  45. }
  46. }
  47. public static void main(String[] args) {
  48. GuardedObject guardedObject = new GuardedObject();
  49. // t1线程等待t2线程的结果
  50. new Thread(() -> {
  51. log.info("获取结果");
  52. String response = (String) guardedObject.get(1500);
  53. log.info("结果{}", response);
  54. }, "t1").start();
  55. new Thread(() -> {
  56. log.info("执行任务");
  57. try {
  58. TimeUnit.SECONDS.sleep(2);
  59. } catch (InterruptedException e) {
  60. e.printStackTrace();
  61. }
  62. guardedObject.complete(new String("hello"));
  63. }, "t2").start();
  64. }
  65. }