/**
*模拟线程不安全问示例1:买票
*执行结果:可以看到第4、3张票卖了两次,还有人买到了第0张票
?*/
public class MyTicker {
????public static void main(String[] args) throws InterruptedException {
????????BuyTicker ticker = new BuyTicker();
????????Thread person1Thread = new Thread(ticker, "person1");
????????Thread person2Thread = new Thread(ticker, "person2");
????????Thread person3Thread = new Thread(ticker, "person3");
????????person1Thread.start();
????????person2Thread.start();
????????person3Thread.start();
????}
}
class BuyTicker implements Runnable{
//车票
????private int tickerNum = 10;
//停止线程标识
????boolean flag = true;
????@Override
????public void run() {
????????while (flag) {
????????????try {
????????????????buyTicker();
????????????} catch (InterruptedException e) {
????????????????e.printStackTrace();
????????????}
????????}
????}
????private void buyTicker() throws InterruptedException {
//判断是否还有票
????????if (tickerNum <= 0) {
????????????flag = false;
????????????return;
????????}
//模拟延时
????????Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "买到第" + tickerNum -- + "张票");
????}
}