理解多线程卖票demo
- Lock架构
- 使用lock替代synchronized
- 总结
使用Lock 实现。
Lock架构
使用lock替代synchronized
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** 企业级的多线程代码* 在高内聚低耦合情况下 多线程 操作 资源类* @author echo lovely* @date 2021/2/15 13:08*/class Ticket {private int num = 30;// 创建锁Lock lock = new ReentrantLock();void sale() {lock.lock();try {if (this.num > 0)System.out.println(Thread.currentThread().getName() + " 当前票数: " + this.num -- + "\t还剩下票数: " + num);} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}}public class Demo01 {public static void main(String[] args) {// 开启三个线程同时卖票Ticket ticket = new Ticket();new Thread(() -> {for (int i = 0; i < 30; i++) {ticket.sale();}} , "A").start();new Thread(() -> {for (int i = 0; i < 30; i++) {ticket.sale();}} , "B").start();new Thread(() -> {for (int i = 0; i < 30; i++) {ticket.sale();}} , "C").start();}}
总结
模板代码:
try {lock.lock();// todo sth...} catch (Exception e) {e.printStackTrace();
} finally {// 释放资源lock.unlock();
}
使用Thread类创建线程套路写法:
new Thread(Runnable r, String threadName);// lambda替代了Runnable接口中的 run方法
new Thread(() -> { // 线程业务方法 }, "your thread name...");