案例:多个线程同时操作同一个对象:买火车票的例子【多线程操作不安全咋处理呢?】
package com.chengguo.线程; /** * 多个线程同时操作同一个对象:买火车票的例子【多线程操作不安全咋处理呢?】 */ public class Demo_20200509002_Thread implements Runnable { //定义火车票默认张数 private int ticketNums = 10; @Override public void run() { while (true) { if (ticketNums <= 0) { break; } else { try { //模拟延时 Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } //获取当前票的名字:Thread.currentThread().getName();每抢一张票就-- System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票"); } } } public static void main(String[] args) { //创建runnable接口的实现类对象 Demo_20200509002_Thread dt1 = new Demo_20200509002_Thread(); //创建一个线程对象,通过线程对象来开启线程 new Thread(dt1,"A").start(); new Thread(dt1,"B").start(); new Thread(dt1,"C").start(); } }