Java共享锁 模拟应用场景

package com.mgk.threads.shared;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 共享锁
 * Semaphore(int num)
 * num 参数含义,允许多个线程共同运行。只有当之前的线程释放后,后续的线程还才可运行。
 * 
 */
public class TestThread {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        Lock lock = new ReentrantLock();
       new Thread( new ThreadA(semaphore,lock),"qx").start();
        new Thread( new ThreadA(semaphore,lock),"sc").start();
        new Thread( new ThreadA(semaphore,lock),"gk").start();
    }
}
class ThreadA implements  Runnable{
    private volatile   static int count  = 2;
    private Lock lock;
    private  Semaphore semaphore ;
    public  ThreadA(Semaphore semaphore, Lock lock){
        this.semaphore = semaphore;
        this.lock=lock;
    }
    private int get(){
        this.lock.lock();
        try {
            return  --count;
        }finally {
            this.lock.unlock();
        }
    }
    private int exit(){
        this.lock.lock();
        try {
            return  ++count;
        }finally {
            this.lock.unlock();
        }
    }
    @Override
    public void run() {
        try {
            this.semaphore.acquire();
            System.out.println(Thread.currentThread().getName() +"进入停车厂,剩余车位:" + get());
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() +"出入停车厂,剩余车位:" + exit());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
        }
    }
}


停车场就两个停车位
也就是只能允许两个线程进去然后争夺锁钥匙停车
当有车出去后,空出停车场位置,下一辆车才允许进来

 

 

如果不释放锁会一直阻塞状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值