1. public class WaitNotify {
    2. static Object lock = new Object();
    3. static boolean flag = true;
    4. public static void main(String[] args) throws InterruptedException {
    5. Thread waitThread = new Thread(new Wait(), "WaitThread");
    6. waitThread.start();
    7. TimeUnit.SECONDS.sleep(1);
    8. Thread notifyThread = new Thread(new Notify(), "notifyThread");
    9. notifyThread.start();
    10. }
    11. static class Wait implements Runnable {
    12. @Override
    13. public void run() {
    14. synchronized (lock) {
    15. while (flag) {
    16. System.out.println(Thread.currentThread() + "flag is true. wait@" + LocalDateTime.now());
    17. try {
    18. lock.wait();
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. System.out.println(Thread.currentThread() + "flag is false. running@" + LocalDateTime.now());
    24. }
    25. }
    26. }
    27. static class Notify implements Runnable {
    28. @Override
    29. public void run() {
    30. //加锁
    31. synchronized (lock){
    32. System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
    33. //获取到lock锁之后,notifyAll,修改flag
    34. lock.notifyAll();
    35. flag = false;
    36. try {
    37. Thread.sleep(1000);
    38. } catch (InterruptedException e) {
    39. e.printStackTrace();
    40. }
    41. }
    42. try {
    43. Thread.sleep(1000);
    44. } catch (InterruptedException e) {
    45. e.printStackTrace();
    46. }
    47. synchronized (lock){
    48. System.out.println(Thread.currentThread() + "hold lock. notify@" + LocalDateTime.now());
    49. try {
    50. Thread.sleep(50000);
    51. } catch (InterruptedException e) {
    52. e.printStackTrace();
    53. }
    54. }
    55. }
    56. }
    57. }

    image.png

    WaitThread首先获得了对象的锁,然后调用对象的wait()方法,释放锁,进入了等待队列中,线程状态为waiting;NotifyThread获得了对象的锁,并调用对象的notify()方法,将WaitThread从等待队列移到同步队列中,此时WaitThread的状态变为阻塞Blocked,等待NotifyThread执行完之后释放锁之后WaitThread获取到锁之后0从wait()方法返回并继续执行。