package com.java.concurrent;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/***
* 一、用于解决多线程安全问题的方式 sychronized:隐式锁 1.同步代码块 2.同步方法
*
* jdk1.5以后 3.同步锁Lock 注意:是一个显示锁,需要通过lock()方法上锁,必须通过unlock()方法进行释放锁。
*
* @author fliay
*
*/
public class TestLock {
public static void main(String[] args) {
Ticket t = new Ticket();
new Thread(t, "窗口1").start();
new Thread(t, "窗口2").start();
new Thread(t, "窗口3").start();
}
}
class Ticket implements Runnable {
private int tick = 100;
private Lock lock = new ReentrantLock();
public void run() {
/*
* 多个窗口同时售票,会出现一票多卖的情况 while(tick>0){
* System.out.println(Thread.currentThread().getName()+"完成售票,余票为:"+
* --tick); }
*/
while (true) {
lock.lock();
try {
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (tick > 0) {
System.out.println(Thread.currentThread().getName() + "完成售票,余票为:" + --tick);
}
} finally {
lock.unlock();
}
}
}
}