初识并发(购买火车票)
购买火车票
- 发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱。
Code:
public class TicketDemo_04 implements Runnable{private int ticketNumber = 10; // 票数@Overridepublic void run() {while (true){if (ticketNumber <= 0) {break;}try {Thread.sleep(200); // 线程休眠,CPU太快导致票都被一个人抢了,所以需要休眠} catch (InterruptedException e) {e.printStackTrace();}// Thread.currentThread().getName() : 获取线程name System.out.println(Thread.currentThread().getName()+"抢到了"+ticketNumber-- +"票"); }}public static void main(String[] args) {TicketDemo_04 td = new TicketDemo_04();new Thread(td,"云疏").start();new Thread(td,"若瑄").start();new Thread(td,"淼淼").start();}
}