import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class ReentryLockTest { private static void test(ReentrantLock lock,String threadName) { Boolean isLocked = lock.isLocked(); if (isLocked) { System.out.println(threadName+" 当前锁被锁住了,等待中......."); } lock.lock(); System.out.println(threadName+" 获得锁......."); try { TimeUnit.SECONDS.sleep((int)Math.random()*10); }catch (Exception e) { e.printStackTrace(); } lock.unlock(); System.out.println(threadName+" 释放当前锁."); } public static void main(String[] args) { List<ReentrantLock> list =new ArrayList<>(); ReentrantLock lock1 = new ReentrantLock(); ReentrantLock lock2 = new ReentrantLock(); ReentrantLock lock3 = new ReentrantLock(); ReentrantLock lock6 = new ReentrantLock(); list.add(lock1); list.add(lock2); list.add(lock3); list.add(lock1); list.add(lock1); list.add(lock6); list.add(lock1); list.add(lock1); long start = System.currentTimeMillis(); for (int i =0 ;i< 8;i++) { ReentrantLock lock = list.get(i); int index = i; new Thread(()->{ String name = lock.toString().substring(lock.toString().length()-15,lock.toString().length()-11); test(lock,Thread.currentThread().getName()); }).start(); } long end = System.currentTimeMillis(); System.out.println(end -start+"毫秒"); } }
ReentrantLock 可重入锁测试
最新推荐文章于 2022-05-15 08:16:21 发布