1 什么是线程锁
两个或以上线程在访问共享资源时,为了确保这个共享资源被每个线程访问结果正确,这时就需要用到线程锁。
2 线程锁使用场景
a)多个窗口同时售票问题
b)公交车前后门上车抢坐问题
3 使用线程锁,解决多个窗口同时售票问题
public class TicketTask implements Runnable{
private int ticket = 100;
private Object lock = new Object();
@Override
public void run() {
while(true){
synchronized (lock) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName() + "买了第" + this.ticket-- + "张票");
}
}
}
}
}
public class Test {
public static void main(String[] args) {
TicketTask task = new TicketTask();
Thread t1 = new Thread(task);t1.setName("窗口一");
Thread t2 = new Thread(task);t2.setName("窗口二");
Thread t3 = new Thread(task);t3.setName("窗口三");
t1.start();
t2.start();
t3.start();
}
}
|
|