自制悲观锁


马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
例 2.2.1.1

package com;
public class Ticket_Pess_MarkToWin {
    private int number=4;
    private int lock=0;
    public synchronized int getLock()
    {
(购买完整教程)
            System.out.println("最后还剩"+number);
        }else{
            System.out.println("不够了,买几张失败");
        }
    }      
  
}





package com;
class MulThreMarkToWin extends Thread {
    Ticket_Pess_MarkToWin ticPes_MarkToWin;
    public MulThreMarkToWin(Ticket_Pess_MarkToWin ticPes_MarkToWin) {
(购买完整教程)
            System.out.println("没拿到锁,没干成");
        }
    }
}
class MulThreMarkToWinBatch extends Thread {
    Ticket_Pess_MarkToWin ticPes_MarkToWin;
    public MulThreMarkToWinBatch(Ticket_Pess_MarkToWin ticPes_MarkToWin) {
        this.ticPes_MarkToWin=ticPes_MarkToWin;
    }
    public void run() {
(购买完整教程)
    }
}
public class TestConcurBuy_MarkToWin {
    public static void main(String[] args) {
        Ticket_Pess_MarkToWin ticPes_MarkToWin=new Ticket_Pess_MarkToWin();
        Thread t1 = new MulThreMarkToWin(ticPes_MarkToWin);
        Thread t2 = new MulThreMarkToWinBatch(ticPes_MarkToWin);
        Thread t3 = new MulThreMarkToWin(ticPes_MarkToWin);
        t1.start();
        t2.start();
        t3.start();
    }
}


输出结果:


锁的synchronized,导致等很长时间,用睡觉来模拟
买一张成功
最后还剩3
锁的synchronized,导致等很长时间,用睡觉来模拟
买一张成功
最后还剩2
锁的synchronized,导致等很长时间,用睡觉来模拟
不够了,买几张失败


再运行一遍,可能输出的结果是:


锁的synchronized,导致等很长时间,用睡觉来模拟
买一张成功
最后还剩3
锁的synchronized,导致等很长时间,用睡觉来模拟
买几张成功
最后还剩0
锁的synchronized,导致等很长时间,用睡觉来模拟
不够了,买一张失败