昨日之深渊,今日之浅谈
—— 24.5.25
一、Lock对象的介绍和基本使用
1.概述
Lock是一个接口
2.实现类
ReentrantLock
3.方法
lock()获取锁
unlock()释放锁
4.Lock锁的使用
package S78Lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MyTicket implements Runnable{ // 定义100章票 int ticket = 100; // 创建lock对象 Lock lock = new ReentrantLock(); @Override public void run(){ while(true){ try{ Thread.sleep(100L); // 获取锁 lock.lock(); if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "买了第" + ticket + "张票"); ticket--; } } catch (InterruptedException e) { throw new RuntimeException(e); }finally { // 释放锁 lock.unlock(); } } } }
package S78Lock; public class Demo217Test { public static void main(String[] args) { // new一次,分别传递到三个线程对象中去 MyTicket myTicket = new MyTicket(); System.out.println(myTicket); Thread th1= new Thread(myTicket, "赵四"); Thread th2= new Thread(myTicket, "刘能"); Thread th3= new Thread(myTicket, "广坤"); th1.start(); th2.start(); th3.start(); } }
仍然是线程安全的
5.synchronized和Lock锁的区别
synchronized:不管是同步代码块还是同步方法,都需要在结束{}后,释放锁对象
Lock:通过两个方法控制需要被同步的代码,更加灵活