同步问题的引出

    1. public class Test extends Object {
    2. public static void main(String[] args) throws Exception {
    3. Runnable myThread = new MyThread();
    4. Thread thread0 = new Thread(myThread);
    5. Thread thread1 = new Thread(myThread);
    6. Thread thread2 = new Thread(myThread);
    7. Thread thread3 = new Thread(myThread);
    8. Thread thread4 = new Thread(myThread);
    9. thread0.start();
    10. thread1.start();
    11. thread2.start();
    12. thread3.start();
    13. thread4.start();
    14. }
    15. }
    16. //线程操作类
    17. class MyThread implements Runnable {
    18. private int ticket = 5;
    19. @Override
    20. public void run() {
    21. for (int i = 0; i < 50; i++) {
    22. if (this.ticket > 0) {
    23. try {
    24. Thread.sleep(500);
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. }
    28. this.ticket--;
    29. System.out.println(Thread.currentThread().getName() + "余票:" + this.ticket);
    30. }
    31. }
    32. }
    33. }

    结果截图
    image.png