ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentantLock,可以显式加锁、释放锁
synchronized与Lock的对比
-
Lock是显式锁(手动开启和关闭的锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放
-
Lock只有代码块锁,synchronized有代码块锁和方法锁
-
使用Lock锁,JVM将花费较少时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
-
优先使用顺序:Lock>同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)
//格式 class A{ private final ReentrantLock lock = new ReentrantLock(); public void m(){ lock.lock(); try{ //保证线程安全的代码 }finally { lock.unlock(); //如果同步代码有异常,要将unlock()写入finally语句块 } } }
package oop.dxcgaoji; import java.util.concurrent.locks.ReentrantLock; //测试Lock锁 public class TestLock { public static void main(String[] args) { TestLock2 testLock2 = new TestLock2(); new Thread(testLock2).start(); new Thread(testLock2).start(); new Thread(testLock2).start(); } } class TestLock2 implements Runnable{ int ticketNums = 10; //定义Lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try{ lock.lock();//加锁 if (ticketNums>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticketNums--); }else { break; } }finally { lock.unlock();//解锁 } } } }
搜索
复制
标签:Thread,Lock,ReentrantLock,lock,new,多线程,public From: https://www.cnblogs.com/sususyq-/p/16609317.html