同步锁Lock

2018-03-13  本文已影响10人  zheting

用于解决多线程安全问题的方式:
synchronized 隐式锁

  1. 同步代码块
  2. 同步方法

jdk1.5后新增

  1. 同步锁Lock
    注意:是一个显式锁,需要通过lock()方法上锁,必须通过unlock()方法释放锁。
package com.sheting.concurrent.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Create Time: 2018-03-09 11:04
 *
 * @author sheting
 */
public class TeskLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "窗口2").start();
        new Thread(ticket, "窗口1").start();
        new Thread(ticket, "窗口3").start();
    }
}

class Ticket implements Runnable {
    private int ticks = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //添加锁
            lock.lock();
            try {
                if (ticks > 0) {
                    Thread.sleep(300);
                    System.out.println(String.format("%s, 余票为:%s", Thread.currentThread().getName(), --ticks));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //释放锁
                lock.unlock();
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读