自制乐观锁

ii)自制乐观锁:

例 2.2.1.2

package com;
public class Ticket_Opti_MarkToWin {
    private int number=4;
    private int numberVersion=0;
    private synchronized int updAtom(int num,int verNum)
    {
        int flag;
        if(numberVersion==verNum&&number>num){

        return flag;
    }
    
    void buyOne()
    {
/*前面的三句,都只是get,想改只有updAtom里面,
 你的buyOne只有改对和不改的权利,没有改错的权利*/        
        int myVersion=numberVersion;

        if(flag==1){
            System.out.println("买一张成功");
        }else{
            System.out.println("已经进队等了一会,买一张失败");
        }
    }
    
    void buyBatch(int num)
    {
        int myVersion=numberVersion;
        int myNumber=number;

    }
    
}



package com;
class MulThreMarkToWin extends Thread {
    Ticket_Opti_MarkToWin ticOpti_MarkToWin;

}
class MulThreMarkToWinBatch extends Thread {
    Ticket_Opti_MarkToWin ticOpti_MarkToWin;

}
public class TestConcurBuy_MarkToWin {
    public static void main(String[] args) {
        Ticket_Opti_MarkToWin ticOpti_MarkToWin=new Ticket_Opti_MarkToWin();
        Thread t1 = new MulThreMarkToWin(ticOpti_MarkToWin);
        Thread t2 = new MulThreMarkToWinBatch(ticOpti_MarkToWin);
        Thread t3 = new MulThreMarkToWin(ticOpti_MarkToWin);
        Thread t4 = new MulThreMarkToWin(ticOpti_MarkToWin);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

 


更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44638460/article/details/104137404

posted @ 2022-03-19 18:36  malala  阅读(13)  评论(0编辑  收藏  举报