lock鎖(JDK1.5後新增)
阿新 • • 發佈:2022-04-19
lock鎖(JDK1.5後新增)
-
鎖的優先使用級
lock>程式碼鎖>方法鎖
程式碼塊鎖synchronized的this指的是同一個demo012;
package com.Thread; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TrainTicket extends Thread{ static int trainticket =10; public TrainTicket(String name) { super(name); } //lock是一個介面;必須呼叫他的實現類 Lock lock = new ReentrantLock(); public void run() { //把鎖關上 lock.lock(); //有100人在搶票 for(int i = 1;i<=100;i++){ if(trainticket>0){ System.out.println("我搶到了火車票;第"+trainticket--+"張;從"+this.getName()+"視窗"); } } //把鎖開啟 lock.unlock(); } }
package com.Thread; public class Demo011 { public static void main(String[] args) { Demo012 demo012 = new Demo012(); Thread thread = new Thread(demo012,"1號"); thread.start(); Thread thread2 = new Thread(demo012,"2號"); thread2.start(); Thread thread3 = new Thread(demo012,"3號"); thread3.start(); } }