0
点赞
收藏
分享

微信扫一扫

一 简单使用ReentrantLock

Separes 2022-03-15 阅读 84

ReentrantLock

ReentrantLock 实现同步

public class ReentrantLockTest {

    static ReentrantLock reentrantLock = new ReentrantLock(); // 声明ReentrantLock

    public static void main(String[] args) {
        try {
            reentrantLock.lock(); // 加锁
            // ----
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock(); // 解锁
        }

    }
}

Condition 讲解

简单实现

public class MyService {

    private ReentrantLock reentrantLock = new ReentrantLock();
    private Condition condition = reentrantLock.newCondition();
    private List<String> arrayList = new ArrayList<>();

    public void addItems() {
        try {
            reentrantLock.lock();
            if (arrayList.size() <= 0) {
                arrayList.add("新增一跳数据");
                System.out.println("addItems -- > 开始等待删除");
                condition.await();
            }
            System.out.println("addItems -- > 执行完了");
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }


    public void removeItems() {
        try {
            reentrantLock.lock();
            if (arrayList.size() >= 0) {
                arrayList.remove(0);
                System.out.println("removeItems -- > 元素已删除");
                condition.signal();
            }
            System.out.println("removeItems -- > 执行完了");
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }

}
  • 运行类
public class Run {

    public static void main(String[] args) throws InterruptedException {
        MyService myService = new MyService();
        new Thread(() -> {
            myService.addItems();
        }).start();
        Thread.sleep(1000);
        new Thread(() -> {
            myService.removeItems();
        }).start();
    }
}

唤醒指定线程

public class MyService {
    private ReentrantLock reentrantLock = new ReentrantLock();
    private Condition condition = reentrantLock.newCondition();
    private Condition conditionA = reentrantLock.newCondition();
    public void awaitA() {
        try {
            reentrantLock.lock();
            System.out.println("conditionA await 时间:" + System.currentTimeMillis());
            conditionA.await();
            System.out.println("conditionA 唤醒 时间:" + System.currentTimeMillis());
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }
    public void await() {
        try {
            reentrantLock.lock();
            System.out.println("condition await 时间:" + System.currentTimeMillis());
            condition.await();
            System.out.println("condition 唤醒 时间:" + System.currentTimeMillis());
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }
    public void signalA() {
        try {
            reentrantLock.lock();
            System.out.println("conditionA signal 时间:" + System.currentTimeMillis());
            conditionA.signal();
            System.out.println("conditionA signal 结束时间:" + System.currentTimeMillis());
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }
}
  • 运行类
public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyService myService = new MyService();
        new Thread(() -> {
            myService.await();
        }).start();
        new Thread(() -> {
            myService.awaitA();
        }).start();
        Thread.sleep(1000);
        new Thread(() -> {
            myService.signalA();
        }).start();
    }
}

公平锁与非公平锁

  • 声明公平锁与非公平锁的方式
   // 默认非公平锁
    public ReentrantLock() {
        sync = new NonfairSync();
    }
    // 传递 true = 公平锁, false = 非公平锁
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

公平锁

public class MyService {
    private ReentrantLock reentrantLock = new ReentrantLock(true);

    public void awaitA() {
        try {
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + "_ 获得锁");
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }
}
  • 运行类
public class Run {

    public static void main(String[] args) throws InterruptedException {
        MyService myService = new MyService();
        List<Thread> arr = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            Thread thread = new Thread(() -> {
                System.out.println(Thread.currentThread().getName()+"_ 运行了");
                myService.awaitA();
            }, i + "");
            arr.add(thread);
        }
        for (Thread thread : arr) {
            thread.start();
        }
    }
}
  • 输出结果
0_ 运行了
4_ 运行了
2_ 运行了
3_ 运行了
1_ 运行了
0_ 获得锁
4_ 获得锁
2_ 获得锁
3_ 获得锁
1_ 获得锁

非公平锁

public class MyService {
    private ReentrantLock reentrantLock = new ReentrantLock(false);

    public void awaitA() {
        try {
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + "_ 获得锁");
        } catch (Exception e) {

        } finally {
            reentrantLock.unlock();
        }
    }
}

  • 输出结果
0_ 运行了
3_ 运行了
2_ 运行了
4_ 运行了
1_ 运行了
0_ 获得锁
3_ 获得锁
2_ 获得锁
4_ 获得锁
1_ 获得锁

关键方法

hasQueuedThread(Thread thread)

HasQueuedThreads()

hasWaiters()

hasQueueLength()

isFair()

isHeldByCurrentThread()

isLocked()

lockInterruptibly()

tryLock()

tryLock(long timeout, TimeUnit unit)

Condition#awaitUninterruptibly

举报

相关推荐

0 条评论