多线程关键字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();
        }

    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值