1.重入锁和synchronized比较
特征 | synchronized | reentrantLock |
底层原理 | JVM实现 | JDK实现 |
性能区别 | 低->高(JDK5+) | 高 |
锁的释放 | 自动释放(编译器保证) | 手动释放(finally保证) |
编码程度 | 简单 | 复杂 |
锁的粒度 | 读写不区分 | 读锁、写锁 |
高级功能 | 无 |
公平锁、非公平锁唤醒 Condition分组唤醒 中断等待锁 |
2.代码
public static int users = 100; public static int downTotal = 50000; public static int count = 0; private static ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(users); for (int i = 0; i < downTotal; i++) { executorService.execute(new Runnable() { @Override public void run() { try { semaphore.acquire(); add(); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("下载总数为:"+count); } private static void add() { lock.lock(); try { count++; } finally { lock.unlock();//一定要放在finally中,防止死锁 } }
标签:重入,int,lock,ReentrantLock,finally,static,public From: https://www.cnblogs.com/blanset/p/16785852.html