Lock锁:
通过显式定义锁实现同步。
java.util.concurrent,locks.lock接口是控制多个线程对共享资源进行访问的工具。锁可以对共享资源的独占访问,每次只能有一个线程对lock对象加索,线程开始访问共享资源前先获得lock对象。
ReentrantLock类实现了Lock,拥有于synchronized相同的并发性和内存语义,比较常用。
class A{ private final ReentrantLock lock = new ReentrantLock(); public void m() { try { lock.lock(); //保证线程安全的代码 }finally { lock.unlock(); } } }
public class Lock { public static void main(String[] args) { BuyTickett buyTicket = new BuyTickett(); new Thread(buyTicket,"a").start(); new Thread(buyTicket,"b").start(); new Thread(buyTicket,"c").start(); } } class BuyTickett implements Runnable{ private int ticketNum = 10; boolean flag = true; private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (flag){ try { lock.lock(); try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } }finally { lock.unlock(); } } } private void buy() throws InterruptedException { if (ticketNum <= 0){ flag = false; return; } Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"获得了第"+ticketNum--+"张票"); } }
b获得了第10张票 b获得了第9张票 c获得了第8张票 c获得了第7张票 c获得了第6张票 c获得了第5张票 c获得了第4张票 c获得了第3张票 a获得了第2张票 a获得了第1张票
Lock锁与synchronized对比: