失去最大客戶!美光:缺少華為需求,2021 年記憶體或供需失衡
阿新 • • 發佈:2020-10-01
概述
通過加鎖、解鎖,鎖住一段程式碼塊
例項
/** * 鎖 */ public class TestLock { public static void main(String[] args) { MyLock myLock1 = new MyLock(); Thread t1 = new Thread(myLock1); Thread t2 = new Thread(myLock1); Thread t3 = new Thread(myLock1); t1.start(); t2.start(); t3.start(); } } class MyLock implements Runnable { private int ticket = 10; private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try { lock.lock(); if(ticket <= 0){ return; } Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+"拿到了票 : "+ticket--); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } } }