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(); } }