java 线程安全 Lock

一、语法

1、锁对象

ReentrantLock lock = new ReentrantLock();

2、上下锁

// 上锁
lock.lock();
// 安全代码
// 解锁
lock.unlock();

二、案例

1、线程类

package com.wt.lock;

import java.util.concurrent.locks.ReentrantLock;

public class Demon01Lock implements Runnable{
    public int tick = 100;

    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(100L);
                // 上锁
                lock.lock();
                // 安全部分代码
                if (tick>0){
                    System.out.println(Thread.currentThread().getName()+"购买了第"+tick+"张票");
                    tick--;
                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                // 解锁
                lock.unlock();
            }
        }
    }
}

2、主类

package com.wt.lock;

public class Demon01 {
    public static void main(String[] args) {
        Demon01Lock demon01Lock = new Demon01Lock();
        Thread thread = new Thread(demon01Lock, "小明");
        Thread thread1 = new Thread(demon01Lock, "小红");
        Thread thread2 = new Thread(demon01Lock, "小白");

        thread.start();
        thread1.start();
        thread2.start();


    }
}

 

posted @ 2025-04-17 19:18  市丸银  阅读(7)  评论(0)    收藏  举报