1. package com.atguigu.java;
    2. import static java.lang.Thread.sleep;
    3. /**
    4. *使用同步方法解决实现Runnable接口的线程安全问题
    5. *
    6. * @author Dxkstart
    7. * @create 2021-05-07 18:02
    8. */
    9. public class WindowTest4 {
    10. public static void main(String[] args) {
    11. //3.创建实现类的对象
    12. Window4 w1 = new Window4();
    13. //4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
    14. Thread t1 = new Thread(w1);
    15. Thread t2 = new Thread(w1);
    16. Thread t3 = new Thread(w1);
    17. //5.通过Thread类的对象调用start()
    18. t1.setName("窗口一:");
    19. t2.setName("窗口二:");
    20. t3.setName("窗口三:");
    21. t1.start();
    22. t2.start();
    23. t3.start();
    24. }
    25. }
    26. // 1.创建一个实现Runnable接口的类
    27. class Window4 implements Runnable {
    28. private int ticket = 100;
    29. //2.实现类去实现Runnable中的抽象方法:run()
    30. @Override
    31. public void run() {
    32. while (true) {
    33. show();
    34. }
    35. }
    36. public synchronized void show(){//同步监视器:this
    37. if (ticket > 0) {
    38. try {
    39. sleep(50);
    40. } catch (InterruptedException e) {
    41. e.printStackTrace();
    42. }
    43. System.out.println(Thread.currentThread().getName() +
    44. "卖票,票号为:" + ticket);
    45. ticket--;
    46. }
    47. }
    48. }