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

多线程 -- 锁 lock

程序员文章站 2022-06-02 08:13:59
...

锁 lock

 

*****************************************

相关接口

 

public interface Lock {

    void lock();   //加锁

    void lockInterruptibly() throws InterruptedException;
                   //加锁,锁可响应中断

    boolean tryLock();
                   //立即获取锁,若不能获得锁,返回false

    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
                   //在指定时间获取锁,若不能获得锁返回false

    void unlock();
                   //释放锁

    Condition newCondition();
                  //生成Condition对象

}

 

接口实现类

ReentrantLock:锁可重入,同一线程可多次获得相同的锁

ReentrantReadWriteLock:读写锁,可实现锁分离,读读不冲突,读写、写写冲突

StampedLock:可实现乐观读,读写不冲突

 


使用示例:

 

class Thread7 implements Runnable{

    private ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        try{
            lock.lock();
            System.out.println("获得lock锁"+" "+Thread.currentThread().getId());
            Thread.sleep(1000);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("释放lock锁:"+" "+Thread.currentThread().getId());
            lock.unlock();
        }
    }
}

public class ThreadTest7 {

    public static void main(String[] args){
        Thread7 t=new Thread7();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        t1.start();
        t2.start();
    }
}

 

***************************************************

控制台输出:

 

获得lock锁 15
释放lock锁: 15
获得lock锁 14
释放lock锁: 14

 

相关标签: