lock锁能够直接看到在哪里加上了锁,在哪里释放了锁
lock():加锁
unlock():释放锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ylh2 implements Runnable{
private static int tickets = 100;
Lock l=new ReentrantLock();
@Override
public void run() {
while (true) {
try{
l.lock();
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在售票第" + tickets + "张");
tickets--;
}}
finally{
l.unlock();}
}
}
}
并且为了保证能够释放锁
所以使用try finally块
public class demo2 {
public static void main(String[] args) {
ylh2 y=new ylh2();
Thread t1=new Thread(y,"窗口1");
Thread t2=new Thread(y,"窗口2");
Thread t3=new Thread(y,"窗口3");
t1.start();
t2.start();
t3.start();
}
}