欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lock的使用

程序员文章站 2024-01-09 18:43:10
...

使用RentrantLock类

在Java多线程中,可以使用synchronized关键字来实现线程之间同步互斥,但在JDK1.5之后加入了RentrantLock类也能达到同样的效果,并且在扩展功能上的也更强大。比如具有嗅探锁定、多路分支通知等功能,在使用上比synchronized更加灵活。

实现同步1

调用lock加锁,unlock解锁

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

public class RentrantLockTest {

    private Lock lock = new ReentrantLock();

    private int count = 0;

    public void test() {
        lock.lock();
        for (int i = 0; i < 5; i++) {
             System.out.println("ThreadName" + Thread.currentThread().getName() + " i = " + i);
        }
        lock.unlock();
    }

    public static void main(String[] args) {
        RentrantLockTest test = new RentrantLockTest();
        ThreadA t1 = new ThreadA(test);
        t1.start();
        ThreadA t2 = new ThreadA(test);
        t2.start();
        ThreadA t3 = new ThreadA(test);
        t3.start();
    }
}

class ThreadA extends Thread {
    private RentrantLockTest test;
    public ThreadA(RentrantLockTest test) {
        this.test = test;
    }
    @Override
    public void run() {
        super.run();
        test.test();
    }
}

运行结果:

ThreadNameThread-0 i = 0
ThreadNameThread-0 i = 1
ThreadNameThread-0 i = 2
ThreadNameThread-0 i = 3
ThreadNameThread-0 i = 4
ThreadNameThread-1 i = 0
ThreadNameThread-1 i = 1
ThreadNameThread-1 i = 2
ThreadNameThread-1 i = 3
ThreadNameThread-1 i = 4
ThreadNameThread-2 i = 0
ThreadNameThread-2 i = 1
ThreadNameThread-2 i = 2
ThreadNameThread-2 i = 3
ThreadNameThread-2 i = 4

当前线程释放锁后其他线程才能获取锁。