ReentrantLock的使用

在多线程开发中,除了synchronized这个关键字外,我们还能通过Lock接口来实现这种效果。通过Lock接口来实现
这种多线程加锁效果的好处是非常的灵活,我们不在需要对整个函数加锁,而且可以很方便的把他放在我们函数的任何
一个地方,非常的称心,而且从效率上来说,使用Lock接口要比使用synchronized关键字效率高一些,下面我们来使用

一个例子来说明这种方法的使用。


1、防止重复执行(忽略重复触发)

 

Java代码   收藏代码
  1. ReentrantLock lock = new ReentrantLock();  
  2. if (lock.tryLock()) {  //如果已经被lock,则立即返回false不会等待,达到忽略操作的效果   
  3.     try {  
  4.         //操作  
  5.     } finally {  
  6.         lock.unlock();  
  7.     }  
  8. }  

 

 

2、同步执行,类似synchronized

 

Java代码   收藏代码
  1. ReentrantLock lock = new ReentrantLock(); //参数默认false,不公平锁  
  2. ReentrantLock lock = new ReentrantLock(true); //公平锁  
  3.   
  4. lock.lock(); //如果被其它资源锁定,会在此等待锁释放,达到暂停的效果  
  5. try {  
  6.     //操作  
  7. finally {  
  8.     lock.unlock();  
  9. }  

 

 

3、尝试等待执行

 

Java代码   收藏代码
  1. ReentrantLock lock = new ReentrantLock(true); //公平锁  
  2. try {  
  3.     if (lock.tryLock(5, TimeUnit.SECONDS)) {      
  4.         //如果已经被lock,尝试等待5s,看是否可以获得锁,如果5s后仍然无法获得锁则返回false继续执行  
  5.         try {  
  6.             //操作  
  7.         } finally {  
  8.             lock.unlock();  
  9.         }  
  10.     }  
  11. catch (InterruptedException e) {  
  12.     e.printStackTrace(); //当前线程被中断时(interrupt),会抛InterruptedException                   
  13. }  

 

 

4、可中断锁的同步执行

Java代码   收藏代码
  1. ReentrantLock lock = new ReentrantLock(true); //公平锁  
  2. lock.lockInterruptibly();  
  3. try {  
  4.     //操作  
  5. catch (InterruptedException e) {  
  6.     e.printStackTrace();  
  7. finally {  
  8.     lock.unlock();  
  9. }  

 



public class Job implements Runnable
{

    private PrintQueue printQueue;

    public Job(PrintQueue printQueue)
    {
        this.printQueue = printQueue;
    }

    @Override
    public void run()
    {
        System.out.printf("%s: 要打印一个文档 start \n", Thread.currentThread().getName());
        printQueue.printJob(new Object());
        System.out.printf("%s: 文档被打印出来 end \n", Thread.currentThread().getName());
    }

}


public class PrintQueue
{

    private final Lock queueLock = new ReentrantLock();

    public void printJob(Object document)
    {
        queueLock.lock();
        Long duration = (long) (Math.random() * 10000);
        System.out.println(Thread.currentThread().getName() + ":在PrintQueue:打印一份文档 " + (duration / 1000) + " 秒");
        try
        {
            Thread.sleep(duration);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        finally
        {
            queueLock.unlock();
        }
    }

    public static void main(String[] args)
    {
        PrintQueue printQueue = new PrintQueue();
        Thread thread[] = new Thread[10];
        for (int i = 0; i < 10; i++)
        {
            thread[i] = new Thread(new Job(printQueue), "Thread " + i);
        }
        for (int i = 0; i < 10; i++)
        {
            thread[i].start();
        }
    }


猜你喜欢

转载自blog.csdn.net/yangzongzhuan/article/details/71703416