JavaSE进阶

15.4 线程的同步

  • 问题的提出
    • 多个线程执行的不确定性引起执行结果的不稳定
    • 多个线程对账本的共享,会造成操作的不完整性,会破坏数据。

15.4.1例  题

模拟火车站售票程序,开启三个窗口售票。

class Ticket implements Runnable {

       private int tick = 100;

 

       public void run(){

              while (true) {

                     if (tick > 0) {

                            System.out.println(Thread.currentThread().getName() + "售出车票,tick号为:" + tick--);

                     } else

                            break;

              }

  }

}

 

class TicketDemo {

       public static void main(String[] args) {

 

              Ticket t = new Ticket();

 

              Thread t1 = new Thread(t);

              Thread t2 = new Thread(t);

              Thread t3 = new Thread(t);

              t1.setName("t1窗口");

              t2.setName("t2窗口");

              t3.setName("t3窗口");

              t1.start();

              t2.start();

              t3.start();

       }

}