多线程实现Runnable接口之买车票

public class Thread3 implements Runnable {
    //火车票总数
    private int ticketNums = 10;
    @Override
    public void run() {
        while (true){
            if (ticketNums <= 0){
                break;
            }
            System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- +"张票");
        }
    }

    public static void main(String[] args) {
        Thread3 thread3 = new Thread3();
        new Thread(thread3,"Tenton").start();
        new Thread(thread3,"East").start();
        new Thread(thread3,"黄牛党").start();
  }
}

多个线程操作同一个资源的情况时,线程不安全,出现数据紊乱

加上synchronized,对象只能排队依次买票,确保了线程安全

public class SafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"Tenton").start();
        new Thread(station,"East").start();
        new Thread(station,"黄牛党").start();
    }
}
class BuyTicket implements Runnable{
    //票数
    private int ticket = 10;
    //外部停止方式
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized :同步方法,锁的是this
    private synchronized void buy() {
        //判断是否有票
        if (ticket <= 0){
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- +"张票");
    }
}

posted @ 2020-11-03 14:34  Tenton  阅读(125)  评论(0)    收藏  举报