并发编程-Lock

并发编程之Lock

目录

并发编程之Lock

一、Lock的特点

二、基本语法

三、代码示例

3.1 重入

3.2 可打断(lock.lockInterruptibly())

3.3 超时

3.4 多个条件


一、Lock的特点

  1. 可打断,可重入
  2. 可以设置超时时间
  3. 可以设置为公平锁
  4. 支持多个条件变量
  5. 支持读写锁

二、基本语法

reentrantLock.lock();
try{
    //todo 临界区
}finally{
    reentrantLock.unlock();
}

三、代码示例

3.1 重入

@Slf4j(topic = "liheng")
public class LockTest3 {

    //首先定义一把锁
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        lock1();
    }

    public static void lock1() {
        lock.lock();
        try {
            log.debug("执行lock1");
            //重入
            lock2();
        } finally {
            lock.unlock();
        }
    }
    public static void lock2() {
        lock.lock();
        try {
            log.debug("执行lock2");
        } finally {
            lock.unlock();
        }
    }

}

3.2 可打断(lock.lockInterruptibly())

@Slf4j(topic = "liheng")
public class LockTest4 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();


        //t2首先获取锁 然后阻塞5s
        new Thread(()->{
            try {
                lock.lock();//获取锁
                    log.debug("获取锁----");
                    TimeUnit.SECONDS.sleep(5);
                    log.debug("t2 5s 之后继续执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        },"t2").start();

        //主要是为了让t2先拿到锁
        TimeUnit.SECONDS.sleep(1);

        //t1加锁失败因为被t2持有
        Thread t1 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
                log.debug("t1 获取了锁--执行代码");
            } catch (Exception e) {
                e.printStackTrace();
                log.debug("被打断了没有获取锁");

                return;
            } finally {
                lock.unlock();
            }
        }, "t1");
        t1.start();


        //由于t1 可以被打断 故而1s之后打断t1 不在等待t2释放锁了
        try {
            TimeUnit.SECONDS.sleep(2);
            log.debug("主线程------2s后打断t1");
            //打断t1 清除打断标记
            t1.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

3.3 超时

@Slf4j(topic = "liheng")
public class LockTest5 {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            log.debug("t1启动---------");
            try{
                if (!lock.tryLock(2,TimeUnit.SECONDS)) {//进入if标识拿不到锁
                    log.debug("拿不到锁,返回");
                    return;
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

            try {
                log.debug("获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        //主线程先获取锁
        lock.lock();
        log.debug("主线程程获得了锁");
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } finally {
            lock.unlock();
        }

    }
}
/**
-----------------结果打印-------------------
20:51:52.213 [main] DEBUG liheng - 主线程程获得了锁
20:51:52.215 [t1] DEBUG liheng - t1启动---------
20:51:54.219 [t1] DEBUG liheng - 拿不到锁,返回
*/


lock.tryLock(5,TimeUnit.SECONDS);//将超时时间改为大于主线程睡眠时间3秒 查看打印结果
/**
-----------------结果打印-------------------
20:54:30.658 [main] DEBUG liheng - 主线程程获得了锁
20:54:30.660 [t1] DEBUG liheng - t1启动---------
20:54:33.665 [t1] DEBUG liheng - 获得了锁

*/

3.4 多个条件

@Slf4j(topic = "liheng")
public class LockTest6 {


    static final ReentrantLock lock = new ReentrantLock();
    static boolean isPrettyGril = false; // 女人
    static boolean isMoney = false;//工资

    //没有女人的 waitSet
    static Condition waitpg = lock.newCondition();
    // 没有钱的waitSet
    static Condition waitm = lock.newCondition();


    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            try {
                lock.lock();
                log.debug("有没有女人[{}]", isPrettyGril);
                while (!isPrettyGril) {
                    log.debug("没有女人!等女人");
                    try {
                        waitpg.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("男女搭配干活不累;啪啪啪写完了代码");
            }finally {
                lock.unlock();
            }
        }, "jack").start();


        new Thread(() -> {
            try {
                lock.lock();
                log.debug("有没有工资[{}]", isMoney);
                while (!isMoney) {
                    log.debug("没有工资!等发工资");
                    try {
                        waitm.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("-----卧槽好多钱;啪啪啪写完了代码");

            }finally {
                lock.unlock();
            }
        }, "rose").start();


        Thread.sleep(1000);
        new Thread(() -> {
            try {
                lock.lock();
                isMoney = true;
                log.debug("钱来哦了");

                isPrettyGril=true;
                log.debug("桥老师");
                //waitpg.signal();
                waitm.signalAll();

            }finally {
                lock.unlock();
            }
        }, "boss").start();
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半路笙歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值