lock锁(JDK1.5后添加)
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();
}
}

浙公网安备 33010602011771号