概述
通过加锁、解锁,锁住一段代码块
实例
/**
* 锁
*/
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();
}
}
}
}