LockTest

import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * Description: 解决线程安全问题:Lock锁 -----JDK1.5新特性
 * 面试题:
 *  synchronized与lock锁的区别?
 *  相同
 *      都是解决线程安全问题
 *  不同
 *      synchronized机制自动加锁和释放锁
 *      Lock需要手动加锁并且需要手动释放锁
 *  推荐
 *      建议使用Lock,因为Lock手动加锁 解锁更灵活
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2021-08-15 21:26
 * @see com.songzixian.thread
 */
public class LockTest {

    public static void main(String[] args) {
        Window window= new Window();

        Thread t1 = new Thread(window);
        Thread t2 = new Thread(window);
        Thread t3 = new Thread(window);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}


class Window implements Runnable{

    //模拟100张票
    private int ticket = 100;

    //1.实例化lock锁
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public  void run() {
        while (true){
           try {
               //调用lock方法解锁
               lock.lock();
                Thread.sleep(50);
               if (ticket >0){
                   System.out.println(Thread.currentThread().getName()+"售票:票号为"+ticket);
                   ticket--;
               }else {
                   break;
               }
           }catch (InterruptedException e){
               e.printStackTrace();
           }finally {
               //unlock 手动解锁
                lock.unlock();
           }
        }
    }

}

注意:如果同步代码有异常,要将unlock()写入finally语句块,建议开发中都讲unlock()放进finally中

Last modification:August 16, 2021
如果觉得这篇技术文章对你有用,请随意赞赏