新手:ReentrantLock和synchronized的小测试

package com.qiansi.szy.mqtt;

import java.util.concurrent.locks.ReentrantLock;

public class Test1 implements Runnable {
    private int tickets = 100;
    ReentrantLock lock=new ReentrantLock(false);
    @Override
    public void run() {

//只能一个卖:synchronized
//        synchronized (this) {
//            while (tickets > 0) {
//                if (tickets > 0) {
//                    System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
//                    tickets--;
//                }
//            }
//        }
//只能一个卖:lock方法
//        lock.lock();
//        try {
//            while (tickets > 0) {
//                if (tickets > 0) {
//                    System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
//                    tickets--;
//                }
//            }
//        } catch (Exception e) {
//
//        } finally {
//            lock.unlock();
//        }
//只保证票数正确,大家都可以卖:synchronized
        while (tickets > 0) {
            synchronized (this) {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
                    tickets--;
                }
            }
        }
//只保证票数正确,大家都可以卖: lock方法
//        while (tickets > 0) {
//            lock.lock();
//            try {
//                if (tickets > 0) {
//                    System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
//                    tickets--;
//                }
//            } catch (Exception e) {
//
//            } finally {
//                lock.unlock();
//            }
//        }
    }
    public static void main(String[] args) {
        Test1 tt = new Test1();
        Thread th1 = new Thread(tt, "1号窗口");
        Thread th2 = new Thread(tt, "2号窗口");
        th1.start();
        th2.start();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值