wait notify 版

  1. public class Test25 {
  2. static final Object lock = new Object();
  3. // 表示 t2 是否运行过
  4. static boolean t2runned = false;
  5. public static void main(String[] args) {
  6. Thread t1 = new Thread(() -> {
  7. synchronized (lock) {
  8. while (!t2runned) {
  9. try {
  10. lock.wait();
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. log.debug("1");
  16. }
  17. }, "t1");
  18. Thread t2 = new Thread(() -> {
  19. synchronized (lock) {
  20. log.debug("2");
  21. t2runned = true;
  22. lock.notify();
  23. }
  24. }, "t2");
  25. t1.start();
  26. t2.start();
  27. }
  28. }

Park Unpark 版

  1. public class Test26 {
  2. public static void main(String[] args) {
  3. Thread t1 = new Thread(() -> {
  4. LockSupport.park();
  5. log.debug("1");
  6. }, "t1");
  7. t1.start();
  8. new Thread(() -> {
  9. log.debug("2");
  10. LockSupport.unpark(t1);
  11. },"t2").start();
  12. }
  13. }