package com.wuming.demo01;
//多个线程同时操作同一个对象
//买火车票例子
//多个线程操作下不安全,出现紊乱
public class TestThread4 implements Runnable{/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see Thread#run()*///票数private int ticketNums=10;@Overridepublic void run() {while(true){if (ticketNums<=0){break;}//模拟延时try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票");}}public static void main(String[] args) {TestThread4 ticket = new TestThread4();new Thread(ticket,"小明").start();new Thread(ticket,"老师").start();new Thread(ticket,"黄牛党").start();}
}
 
老师-->拿到了第10票
 黄牛党-->拿到了第9票
 小明-->拿到了第8票
 小明-->拿到了第6票
 老师-->拿到了第5票
 黄牛党-->拿到了第7票
 小明-->拿到了第4票
 老师-->拿到了第3票
 黄牛党-->拿到了第2票
 黄牛党-->拿到了第1票
 老师-->拿到了第0票
 小明-->拿到了第-1票