package com.xhpc.payment.lock;

import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.utils.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yuyang
 * @date 2023-08-22 15:55
 */
@RestController
@RequestMapping("/lock")
@Api(value = "测试锁接口", tags = "测试锁接口")
public class LockTestController {

    private int userId;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //写数据
    public void setLockPayment(int userId){
        try{
            readWriteLock.writeLock().lock();//取到写锁
            for (int i = userId; i <10 ; i++) {
                System.out.println(Thread.currentThread().getName()+"准备写入数据");

                this.userId =i;
                System.out.println(Thread.currentThread().getName()+"写入"+this.userId);
                Thread.sleep(2000);
                return;
            }
            userId++;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("858888");
            readWriteLock.writeLock().unlock();//释放锁
        }
    }

    public void getLockPayment(){
        readWriteLock.readLock().lock();//读取到锁
        try{
            System.out.println(Thread.currentThread().getName()+"准备些入数据");
            System.out.println(Thread.currentThread().getName()+"写入"+this.userId);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();//释放锁
        }

    }


    public static void main(String[] args) {
        int number =10;
        LockTestController controller =new LockTestController();
//        System.out.println("准备读取数据");
//        controller.getLockPayment();
//        System.out.println("准备写入数据");
        controller.setLockPayment(number);
//        System.out.println("准备写入数据");
//        controller.setLockPayment(10);
//        System.out.println("准备读取数据");
//        controller.getLockPayment();
//        System.out.println("准备写入数据");
//        controller.setLockPayment(15);
//        String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
//        System.out.println("orderNumber:"+orderNumber);
        System.out.println("number:"+number);
    }
}
