java

线程不安全

rzk · 3月13日 · 2020年本文共444个字 · 预计阅读2分钟83次已读
public class Unsaf睿共享eBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"牛逼的你").start();
        new Thr睿共享ead(station,"可恶的黄牛党").start();
    }

}
class BuyTicke睿共享t implements Runnable{
    //
    private int ticketNnums = 10;
    boolean flag = true;//外部停止
    public void run(){
        //买票
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private  void  buy() throws InterruptedException {
        //判断是否有票
        if (ticketNnums<=0){
            flag = false;
            return;
        }
        //模拟延时
 睿共享       Thread.sleep(1000);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--);
    }
}


这种情况会

2.加入synchronized使方法同步,锁的是this,当前方法
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"牛逼的你").start();
        new Thread(station,"可恶的黄牛党").start();
    }

}
class BuyTicket implements Runnable{
    //
    private int ticketNnums = 10;
    boolean flag = true;//外部停止
    public void run(){
        //买票
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void  buy() throws InterruptedException {
        //判断是否有票
        if睿共享 (ticketNnums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(1000);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--);
    }
}

线程不安全

0 条回应