線程不安全現象---買票

 private static class Count implements Runnable{
        //共有50張車票
        private int num = 50;

    
        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                if (num > 0) {
                    try {
                        //模擬網絡延遲
                        Thread.sleep(100);

                        System.out.println(Thread.currentThread().getName() + "第"
                                + num-- + "號");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

//    public static void main(String[] args) {
//
//        Runnable count= new Count();
//        new Thread(count,"A").start();
//        new Thread(count,"B").start();
//        new Thread(count,"C").start();
//    }

這樣是會有問題的,因爲操作同一個對象。沒有加鎖。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章