多線程關鍵字volatile的使用,記錄變量修改和統計

主要是多線程下靜態變量的值不能及時回寫到運行內存上
用synchronized 或者lock 不加volatile的變量拿不到最新值
public class PersonOne implements Runnable {

 /*   private static int count = 100;
    private static int tatol=0;*/
    private volatile int count = 100;
    private volatile int tatol=0;
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (count > 0) {
            try {
                //lock.lock();
                sale();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
               // lock.unlock();
            }
        }
    }
//public     synchronized    void  sale() {
    public        void  sale() {
        if (count > 0) {
            tatol+=count;
            count--;
            System.out.println(Thread.currentThread().getName() + "正在出售第" + (100 - count) + "票");
            if (count==0){
                System.out.println(tatol);
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] arg) {
        PersonOne personOne = new PersonOne();
        Thread[] t = new Thread[10];
        for (int i = 0; i < 10; i++) {
            t[i] = new Thread(personOne, "窗口" + i);
            t[i].start();
        }

    }
}

 

 

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