Lock锁实现多线程卖票
生活随笔
收集整理的這篇文章主要介紹了
Lock锁实现多线程卖票
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
理解多線程賣票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...");總結
以上是生活随笔為你收集整理的Lock锁实现多线程卖票的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IK分词器应用
- 下一篇: 1标志图片_这四种情况将不再扣分罚款!1