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

Lock的使用

程序员文章站 2024-01-09 18:47:16
...

上一篇我们讲解了synchronized的使用,用它就可以满足数据的同步,但是为什么有时我还是会使用Lock呢?因此在这里我们不得不说说synchronized的不足之处,例如当获取锁的线程执行完要释放锁时,由于某些原因该线程被阻塞了,那么此时并没有将获取的锁释放掉,别的线程也就一直等着锁的释放,这样就很影响程序的执行效率。要解决这个问题,只要让等待的线程不无限期的等待下去就可以了,Lock就完全可以解决这样的问题。

Lock类的使用:
public interface Lock {
    void lock();
    void lockInterruptibly() throws InterruptedException;
    boolean tryLock();
    boolean tryLock(long var1, TimeUnit var3) throws InterruptedException;
    void unlock();
    Condition newCondition();
}

它是个接口类,有6个方法,前面4个就是用来获取锁的,第5个用来释放锁的,第6个用来设置等待和通知;那么下面我们具体操作下这些方法的使用。

lock()的使用
    private Lock lock = new ReentrantLock();
    public void testLock(String name) {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + ",Request Lock...");
        try {
            for (int i = 0; i < 100; i++) {
                y++;
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock ...");
        }
    }

ReentrantLock类实现了接口Lock,新增了一些方法;Lock自己加锁,用完后自己在释放掉锁;如果加锁的程序在运行过程中发生异常,也不会释放锁,那么就需要我们自己进行处理了,所以我们在使用Lock时会将其放入try{}catch{}finally{}中,将释放锁的操作放入finally中。
传入同一实例对象,在两个线程中调用此方法,运行,结果为:

pool-4-thread-1,Request Lock...
TempRunnable->testLock-->CurrThread:pool-4-thread-1 y=1
TempRunnable->testLock-->CurrThread:pool-4-thread-1 y=2
TempRunnable->testLock-->CurrThread:pool-4-thread-1 y=3
pool-4-thread-1,Release Lock...
pool-4-thread-1,Request Lock...
Count Instance 1:-->CurrThread:pool-4-thread-1 y=4
Count Instance 1:-->CurrThread:pool-4-thread-1 y=5
Count Instance 1:-->CurrThread:pool-4-thread-1 y=6
pool-4-thread-1,Release Lock...

从结果上就可以看出,当释放完锁后另一线程才开始申请锁,运行。

tryLock()方法的使用

tryLock()方法具有返回值,得到锁返回true,否则返回false, 看代码:

    public void tryLock(String name) {
        if (lockTry.tryLock()) {
            System.out.println(Thread.currentThread().getName() + ",Request Lock success...");
            try {
                for (int i = 0; i < 3; i++) {
                    y++;
                    System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + ",Release Lock ...");
            }
        } else {
            System.out.println(Thread.currentThread().getName() + ",Request Lock failed...");
        }
    }

传入同一实例对象,在两个线程中调用此方法,运行结果为:

Thread-1,Request Lock success...
Thread-0,Request Lock failed...
Count Instance 1:-->CurrThread:Thread-1 y=1
Count Instance 1:-->CurrThread:Thread-1 y=2
Count Instance 1:-->CurrThread:Thread-1 y=3
Thread-1,Release Lock ...

线程1申请锁成功,线程0申请锁失败了,此时他并没有继续在等待线程1的执行完成。

tryLock(long l, TimeUnit t)方法的使用

tryLock(long l, TimeUnit t)第一个参数表示要等待的时间,第二个参数表示时间单位。
更改上面的方法,如下:

    public void tryLock(String name) {
        try {
            if (lockTry.tryLock(2000, TimeUnit.MILLISECONDS)) {
                System.out.println(Thread.currentThread().getName() + ",Request Lock success...");

                for (int i = 0; i < 3; i++) {
                    y++;
                    System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
                }
            } else {
                System.out.println(Thread.currentThread().getName() + ",Request Lock failed...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockTry.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock ...");
        }
    }

传入同一实例对象,在两个线程中调用此方法,运行结果为:

Thread-1,Request Lock success...
Count Instance 1:-->CurrThread:Thread-1 y=1
Count Instance 1:-->CurrThread:Thread-1 y=2
Count Instance 1:-->CurrThread:Thread-1 y=3
Thread-1,Release Lock ...
Thread-0,Request Lock success...
TempRunnable->TryLock-->CurrThread:Thread-0 y=4
TempRunnable->TryLock-->CurrThread:Thread-0 y=5
TempRunnable->TryLock-->CurrThread:Thread-0 y=6
Thread-0,Release Lock ...

重新设置时间tryLock(1, TimeUnit.MICROSECONDS)之后,传入同一实例对象,在两个线程中调用此方法,运行结果为:

Thread-1,Request Lock success...
Thread-0,Request Lock failed...
Count Instance 1:-->CurrThread:Thread-1 y=1
Count Instance 1:-->CurrThread:Thread-1 y=2
Count Instance 1:-->CurrThread:Thread-1 y=3
Thread-1,Release Lock ...

一个线程在获取到锁之后,另一线程在获取的话肯定就失败了,但是这里设置了时间之后,在获取不到线程的时候就进行等待设定的时间之后在进行获取,获取到了就返回true,获取不到或者中途线程中断了就返回false

lockInterruptibly()的使用

lockInterruptibly()通过这个方法去获取锁时,如果线程 正在等待获取锁,则这个线程能够 响应中断,即中断线程的等待状态。看代码:

    public void interrupt(String name) throws InterruptedException {
        lockTry.lockInterruptibly();
        try {
            for (int i = 0; i < 1000; i++) {
                y++;
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockTry.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock ...");
        }
    }

生成一个线程类TestRunnable,在里面调用interrupt方法,并处理的异常,代码为:

public class TestRunnable implements Runnable {
    private Count count;

    public TestRunnable(Count count) {
        this.count = count;
    }

    @Override
    public void run() {
        try {
            count.interrupt(count.getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(Thread.currentThread().getName() + ",Request Lock Interrupted...");
        }
    }
}

设置中断线程:

        Count count1 = new Count("Count Instance 1:");
        Thread thread1 = new Thread(new TestRunnable(count1));
        Thread thread2 = new Thread(new TestRunnable(count1));
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();

上面代码设置的是休眠10毫秒后,中断thread2;运行代码,看看结果:

MainThread:main started...
TempRunnable->Interrupt-->CurrThread:Thread-0 y=1
......
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898)
......
    at java.lang.Thread.run(Thread.java:745)
......
TempRunnable->Interrupt-->CurrThread:Thread-0 y=507
Thread-1,Request Lock Interrupted...
......
TempRunnable->Interrupt-->CurrThread:Thread-0 y=1000
Thread-0,Release Lock ...

从结果看,10毫秒后,我们中断了正在等待锁的线程thread2,这也说明线程运行时间超出了10毫秒,如果小于10毫秒,那么线程不会被中断,线程thread2会获得锁,并将代码执行完成。
我们在写interrupt方法时,我们将lockTry.lockInterruptibly();写在了try{}catch{}之外,这样异常就从方法抛出,代码为:public void interrupt(String name) throws InterruptedException {};那么我们为什么不把lockTry.lockInterruptibly();写在了try{}catch{}之内呢?我们用代码验证下,将方法更改为:

    public void interrupt(String name) {
        try {
            lockTry.lockInterruptibly();
            for (int i = 0; i < 1000; i++) {
                y++;
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(Thread.currentThread().getName() + ",Request Lock Interrupted...");
        } finally {
            lockTry.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock ...");
        }
    }

运行,结果为:

MainThread:main started...
TempRunnable->Interrupt-->CurrThread:Thread-0 y=1
......
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
    at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
......
    at java.lang.Thread.run(Thread.java:745)
......
TempRunnable->Interrupt-->CurrThread:Thread-0 y=507
Thread-1,Request Lock Interrupted...
......
TempRunnable->Interrupt-->CurrThread:Thread-0 y=1000
Thread-0,Release Lock ...

结果中抛出了异常"Thread-1" IllegalMonitorStateException,它是"Thread-1"抛出来的,但不是中断异常。当线程1在等待锁的过程中,10毫秒后进行了线程中断,执行完成后就会去继续执行finally中的解锁操作,而线程1并没有获取到锁,这样就造成了异常。

因此,对于方法void lockInterruptibly() throws InterruptedException;boolean tryLock(long var1, TimeUnit var3) throws InterruptedException;都应该将调用语句放在try{}catch{}之外。
公平锁的使用

公平锁即尽量以请求锁的顺序来获取锁
看代码的实现:

    private Lock lockFair = new ReentrantLock(true);//true 设置公平锁 false 不设置

    public void fairLock() {
        try {
            lockFair.lock();
            System.out.println(Thread.currentThread().getName() + ",Request Lock...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockFair.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock...");
        }
    }

建立线程类,在生成10个线程,调用此方法:

public class MyRunnable implements Runnable {
    private Count count;
    public MyRunnable(Count count) {
        this.count = count;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " running...");
        count.fairLock();
    }
}

        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            threadList.add(new Thread(new MyRunnable()));
        }

        for (Thread thread1 : threadList) {
            thread1.start();
        }

运行,结果为:

Thread-0 running...
Thread-1 running...
Thread-2 running...
Thread-0,Request Lock...
Thread-4 running...
Thread-3 running...
Thread-1,Request Lock...
Thread-0,Release Lock...
Thread-2,Request Lock...
Thread-1,Release Lock...
Thread-4,Request Lock...
Thread-2,Release Lock...
Thread-4,Release Lock...
Thread-3,Request Lock...
Thread-3,Release Lock...

从结果看,它们是按照请求的顺序,进行锁的申请的。

ReadWriteLock类的使用

来看看的源代码:

public interface ReadWriteLock {
    Lock readLock();
    Lock writeLock();
}

ReadWriteLock类是一个接口类,里面就实现了两个方法:读锁和写锁。它的具体实现类为ReentrantReadWriteLock。我们用代码进行使用演示:

    private ReadWriteLock lock = new ReentrantReadWriteLock();
    private Lock writeLock = lock.writeLock();
    private Lock readLock = lock.readLock();

    public void write(String name) {
        writeLock.lock();
        try {
            for (int i = 0; i < 3; i++) {
                y++;
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Abnormal exit of write method...");
        } finally {
            System.out.println(Thread.currentThread().getName() + ",Release Write Lock ...");
            writeLock.unlock();
        }
    }

    public void read(String name) {
        readLock.lock();
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " output=" + i);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Abnormal exit of read method...");
        } finally {
            System.out.println(Thread.currentThread().getName() + ",Release Read Lock ...");
            readLock.unlock();
        }
    }

上面的两个方法,一个加的是读锁,一个加的是写锁。
生成两个线程,在传入同一实例对象

  • 两个线程都调用read方法,运行:
Thread-0,Request Read Lock ...
Count Instance 1:-->CurrThread:Thread-0 output=0
Count Instance 1:-->CurrThread:Thread-0 output=1
Thread-1,Request Read Lock ...
Count Instance 1:-->CurrThread:Thread-0 output=2
Count Instance 1:-->CurrThread:Thread-1 output=0
Thread-0,Release Read Lock ...
Count Instance 1:-->CurrThread:Thread-1 output=1
Count Instance 1:-->CurrThread:Thread-1 output=2
Thread-1,Release Read Lock ...

从结果看,可以多线程一起读共享数据。

  • 一个线程调用方法read,一个线程调用方法write,运行:
Thread-0,Request Write Lock ...
TempRunnable->WriteLock-->CurrThread:Thread-0 y=1
TempRunnable->WriteLock-->CurrThread:Thread-0 y=2
TempRunnable->WriteLock-->CurrThread:Thread-0 y=3
Thread-0,Release Write Lock ...
Thread-1,Request Read Lock ...
Count Instance 1:-->CurrThread:Thread-1 output=0
Count Instance 1:-->CurrThread:Thread-1 output=1
Count Instance 1:-->CurrThread:Thread-1 output=2
Thread-1,Release Read Lock ...

Thread-0,Request Read Lock ...
Count Instance 1:-->CurrThread:Thread-0 output=0
Count Instance 1:-->CurrThread:Thread-0 output=1
Count Instance 1:-->CurrThread:Thread-0 output=2
Thread-0,Release Read Lock ...
Thread-1,Request Write Lock ...
TempRunnable->WriteLock-->CurrThread:Thread-1 y=1
TempRunnable->WriteLock-->CurrThread:Thread-1 y=2
TempRunnable->WriteLock-->CurrThread:Thread-1 y=3
Thread-1,Release Write Lock ...

从结果看,不管是先调用读还是写,都是一个获取锁执行完成释放锁后,另一个线程才执行。它们之间是互斥的。

  • 两个线程都调用write方法,运行:
Thread-1,Request Write Lock ...
TempRunnable->WriteLock-->CurrThread:Thread-1 y=1
TempRunnable->WriteLock-->CurrThread:Thread-1 y=2
TempRunnable->WriteLock-->CurrThread:Thread-1 y=3
Thread-1,Release Write Lock ...
Thread-0,Request Write Lock ...
TempRunnable->WriteLock-->CurrThread:Thread-0 y=4
TempRunnable->WriteLock-->CurrThread:Thread-0 y=5
TempRunnable->WriteLock-->CurrThread:Thread-0 y=6
Thread-0,Release Write Lock ...

从结果看,它们也是互斥的,只有一个线程执行完释放锁之后,另一个线程才会执行。

读锁和写锁,除了读读外,读写,写读,写写之间都是互斥的。
condition类的使用

condition类,是Java提供的等待/通知类。看看其源码:

public interface Condition {
    //使当前线程加入 await() 等待队列中,并释放当锁,当其他线程调用signal()会重新请求锁。与Object.wait()类似。
    void await() throws InterruptedException;
    //调用该方法的前提是,当前线程已经成功获得与该条件对象绑定的重入锁,否则调用该方法时会抛出IllegalMonitorStateException。
    //调用该方法后,结束等待的唯一方法是其它线程调用该条件对象的signal()或signalALL()方法。等待过程中如果当前线程被中断,该方法仍然会继续等待,同时保留该线程的中断状态。
    void awaitUninterruptibly();
    // 调用该方法的前提是,当前线程已经成功获得与该条件对象绑定的重入锁,否则调用该方法时会抛出IllegalMonitorStateException。
    //nanosTimeout指定该方法等待信号的的最大时间(单位为纳秒)。若指定时间内收到signal()或signalALL()则返回nanosTimeout减去已经等待的时间;
    //若指定时间内有其它线程中断该线程,则抛出InterruptedException并清除当前线程的打断状态;若指定时间内未收到通知,则返回0或负数。
    long awaitNanos(long var1) throws InterruptedException;
    //与await()基本一致,唯一不同点在于,指定时间之内没有收到signal()或signalALL()信号或者线程中断时该方法会返回false;其它情况返回true。
    boolean await(long var1, TimeUnit var3) throws InterruptedException;
   //适用条件与行为与awaitNanos(long nanosTimeout)完全一样,唯一不同点在于它不是等待指定时间,而是等待由参数指定的某一时刻。
    boolean awaitUntil(Date var1) throws InterruptedException;
    //唤醒一个在 await()等待队列中的线程。与Object.notify()相似
    void signal();
   //唤醒 await()等待队列中所有的线程。与object.notifyAll()相似
    void signalAll();
}

使用await()signal()方法,来进行一个简单的实例:

private Lock lockTry = new ReentrantLock();
private Condition condition = lockTry.newCondition();

    public void signal(String name) {
        lockTry.lock();
        System.out.println(name+ "signal:"+ Thread.currentThread().getName() + ",Request Lock...");
        try {
            condition.signal();
            System.out.println(name + "-->CurrThread: Wait for the Thread to wake up...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockTry.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock...");
        }
    }

    public void wait(String name) {
        lockTry.lock();
        System.out.println(name+ "wait:"+Thread.currentThread().getName() + ",Request Lock...");
        try {
            for (int i = 0; i < 5; i++) {
                y++;
                if (i == 2) {
                    System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " is waiting...");
                    condition.await();
                }
                System.out.println(name + "-->CurrThread:" + Thread.currentThread().getName() + " y=" + y);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockTry.unlock();
            System.out.println(Thread.currentThread().getName() + ",Release Lock...");
        }
    }

建立两个线程,分别调用这两个方法;注意线程在调用signal方法时,让线程睡眠几秒,这样在输出结果是就能看出很明显的结果。
运行,结果为:

TempRunnable->Waitwait:Thread-0,Request Lock...
TempRunnable->Wait-->CurrThread:Thread-0 y=1
TempRunnable->Wait-->CurrThread:Thread-0 y=2
TempRunnable->Wait-->CurrThread:Thread-0 is waiting...
Count Instance 1:signal:Thread-1,Request Lock...
Count Instance 1:-->CurrThread: Wait for the Thread to wake up...
Thread-1,Release Lock...
TempRunnable->Wait-->CurrThread:Thread-0 y=3
TempRunnable->Wait-->CurrThread:Thread-0 y=4
TempRunnable->Wait-->CurrThread:Thread-0 y=5
Thread-0,Release Lock...

上一篇:Synchronized的使用