wait notify方式

  1. package org.example.concurrency.test;
  2. import lombok.extern.slf4j.Slf4j;
  3. /**
  4. * @author huskyui
  5. */
  6. @Slf4j
  7. public class Test28 {
  8. static final Object lock = new Object();
  9. static boolean t2Runned = false;
  10. public static void main(String[] args) {
  11. Thread t1 = new Thread(()->{
  12. synchronized (lock){
  13. while (!t2Runned){
  14. try {
  15. lock.wait();
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. if (t2Runned){
  21. log.debug("t1");
  22. }else{
  23. log.debug("not t1");
  24. }
  25. }
  26. });
  27. Thread t2 = new Thread(()->{
  28. synchronized (lock){
  29. t2Runned = true;
  30. log.debug("t2");
  31. lock.notify();
  32. }
  33. });
  34. t1.start();
  35. t2.start();
  36. }
  37. }

park unpark

  1. package org.example.concurrency.test;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.concurrent.locks.LockSupport;
  4. /**
  5. * @author huskyui
  6. */
  7. @Slf4j
  8. public class Test29 {
  9. public static void main(String[] args) {
  10. Thread t1 = new Thread(()->{
  11. LockSupport.park();
  12. log.debug("t1");
  13. });
  14. t1.start();
  15. Thread t2 = new Thread(()->{
  16. log.debug("t2");
  17. LockSupport.unpark(t1);
  18. });
  19. t2.start();
  20. }
  21. }