tryLock 和Lock 和 lockinterruptibly 的区別

tryLock 和Lock 和 lockinterruptibly 的区別
1.tryLock 能获得锁就返回 true,不能就立即返回 false,tryLock(longtimeout,TimeUnit unit),可以增加时间限制,如果超过该时间段还没获得锁,返回 false
2lock能获得锁就返回true,不能的话一直等待获得锁
3.lock 和lockInterruptibly,如果两个线程分别执行这两个方法,但此时中断这两个线程,lock不会抛出异常,而lockInterruptibly 会抛出异常。

第3条小demo案例演示:

package com.coding.webflux.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

public class DemoThread {

    private ReentrantLock lock = new ReentrantLock();
    private final CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        DemoThread demoThread = new DemoThread();
        // 当前线程持有锁,其他线程抢锁期间,lock不会抛中断异常,但是lockInterruptibly抛异常
        new Thread(() -> demoThread.method0()).start();

        // Thread thread = new Thread(() -> demoThread.method1());
        Thread thread = new Thread(() -> demoThread.method2());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        System.out.println("OK");
    }

    /**
     * 使用线程持有锁
     */
    private void method0() {
        try {
            lock.lock();
            Thread.sleep(9999999999L);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 可中断的抢锁
     */
    private void method1() {
        try {
            lock.lockInterruptibly();
            for (int i = 0; i < 10000000; i++) {
                if (i == 5) {
                    latch.countDown();
                }
                System.out.println(".");
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 不可中断的抢锁
     */
    private void method2() {
        try {
            lock.lock();
            for (int i = 0; i < 10000000; i++) {
                if (i == 5) {
                    latch.countDown();
                }
                System.out.println(".");
            }
        } catch (Throwable throwable) {
            System.out.println(throwable.getMessage());
        } finally {
            // 判断当前线程是否占用该锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


}

posted on 2024-09-08 09:13  ~码铃薯~  阅读(24)  评论(0编辑  收藏  举报

导航