ReentrantLock

下面先来看个简单的使用:

package other.thread14;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockService {

    private static ReentrantLock lock = new ReentrantLock();
    
    public void print() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "===" + (i + 1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    
}
package other.thread14;

public class ThreadA extends Thread {
    
    private ReentrantLockService lock;
    
    public ThreadA(ReentrantLockService lock) {
        this.lock = lock;
    }
    
    @Override
    public void run() {
        lock.print();
    }
}
package other.thread14;

public class Test {
    public static void main(String[] args) {
        ReentrantLockService service = new ReentrantLockService();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("1");
        threadA.start();
        ThreadA threadA2 = new ThreadA(service);
        threadA2.setName("2");
        threadA2.start();
        ThreadA threadA3 = new ThreadA(service);
        threadA3.setName("3");
        threadA3.start();
        ThreadA threadA4 = new ThreadA(service);
        threadA4.setName("4");
        threadA4.start();
        ThreadA threadA5 = new ThreadA(service);
        threadA5.setName("5");
        threadA5.start();
    }
}
image.png

从运行的结果来看,当前线程打印完毕之后将锁进行释放,其他线程才可以继续打印。线程打印的数据是分组打印,因为当前线程已经持有锁,但是线程之前打印的顺序是随机的。

你可能感兴趣的:(ReentrantLock)