二十四、锁(Lock)(24、 Lock)

  • 从JDK5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当
  • java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
  • ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
public class ThreadLock implements Runnable{

    private int ticket=10;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            //加锁
            lock.lock();
            while (true){
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName()+"买到的票号:"+ticket--);
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //解锁
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ThreadLock t = new ThreadLock();
        new Thread(t,"张三").start();
        new Thread(t,"李四").start();
        new Thread(t,"王五").start();
    }
}
————————
  • From jdk5 Since 0, Java has provided a more powerful thread synchronization mechanism — realizing synchronization by explicitly defining synchronization lock objects. Synchronous locks use lock objects as
  • java. util. concurrent. locks. Lock interface is a tool that controls multiple threads to access shared resources. Lock provides exclusive access to shared resources. Only one thread can lock the lock object at a time. Threads should obtain the lock object before accessing shared resources
  • Reentrantlock class implements lock. It has the same concurrency and memory semantics as synchronized. Reentrantlock is commonly used in thread safety control, which can explicitly add and release locks.
public class ThreadLock implements Runnable{

    private int ticket=10;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            //加锁
            lock.lock();
            while (true){
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName()+"买到的票号:"+ticket--);
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //解锁
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ThreadLock t = new ThreadLock();
        new Thread(t,"张三").start();
        new Thread(t,"李四").start();
        new Thread(t,"王五").start();
    }
}