1. package com.atguigu.java;
    2. /**
    3. *使用同步方法
    4. *
    5. * @author Dxkstart
    6. * @create 2021-05-07 18:16
    7. */
    8. public class WindowTest5 {
    9. public static void main(String[] args) {
    10. Window5 w1 = new Window5();
    11. Window5 w2 = new Window5();
    12. Window5 w3 = new Window5();
    13. w1.start();
    14. w2.start();
    15. w3.start();
    16. }
    17. }
    18. class Window5 extends Thread {
    19. private static int ticket = 100;//票数
    20. @Override
    21. public void run() {
    22. while(true){
    23. show();
    24. }
    25. }
    26. public static synchronized void show(){//同步监视器:Window5.class
    27. // public synchronized void show(){//同步监视器:w1、w2、w3,此种解决方法时错误的
    28. if(ticket > 0){
    29. try {
    30. sleep(50);
    31. } catch (InterruptedException e) {
    32. e.printStackTrace();
    33. }
    34. System.out.println(Thread.currentThread().getName() + ": 卖票,票号为" + ticket);
    35. ticket --;
    36. }
    37. }
    38. }