Lock锁
怎么使用?怎么把下面的这个锁弄得比较合适,大家都能去买票??
和synchronized相比的好处?
lock的使用规范try finnally
private final ReentrantLock lock = new ReentrantLock();//这样定义的好处?????
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {//这样李白会一个人拿完所有的票
public static void main(String[] args) {
TestLock1 testLock1 = new TestLock1();
Thread t1 = new Thread(testLock1,"李白");
Thread t2 = new Thread(testLock1,"杜甫");
Thread t3 = new Thread(testLock1,"秦始皇");
t1.start();
t2.start();
t3.start();
}
}
class TestLock1 implements Runnable{
private int ticketNum = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try{//规范?
lock.lock();//上锁,与ticketNum有关的代码,但是能不能再缩小范围呢?
if(ticketNum>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("剩余票数"+ticketNum--);
}else{
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}