📜  Java并发-锁接口

📅  最后修改于: 2020-11-15 03:52:46             🧑  作者: Mango


java.util.concurrent.locks.Lock接口用作类似于同步块的线程同步机制。新的锁定机制比同步块更灵活,并提供更多选项。锁和同步块之间的主要区别如下-

  • 顺序保证-同步块不提供对等待线程进行访问的顺序保证。锁接口处理它。

  • 无超时-如果未授予锁定,则同步块没有超时选项。锁定界面提供了这种选择。

  • 单个方法-同步块必须完全包含在一个方法中,而锁接口的方法lock()和unlock()可以在不同的方法中调用。

锁方法

以下是Lock类中可用的重要方法的列表。

Sr.No. Method & Description
1

public void lock()

Acquires the lock.

2

public void lockInterruptibly()

Acquires the lock unless the current thread is interrupted.

3

public Condition newCondition()

Returns a new Condition instance that is bound to this Lock instance.

4

public boolean tryLock()

Acquires the lock only if it is free at the time of invocation.

5

public boolean tryLock()

Acquires the lock only if it is free at the time of invocation.

6

public boolean tryLock(long time, TimeUnit unit)

Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.

7

public void unlock()

Releases the lock.

下面的TestThread程序演示了Lock接口的其中一些方法。在这里,我们使用了lock()来获取锁,然后使用unlock()来释放锁。

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

class PrintDemo {
   private final Lock queueLock = new ReentrantLock();

   public void print() {
      queueLock.lock();

      try {
         Long duration = (long) (Math.random() * 10000);
         System.out.println(Thread.currentThread().getName() 
            + "  Time Taken " + (duration / 1000) + " seconds.");
         Thread.sleep(duration);
      } catch (InterruptedException e) {
         e.printStackTrace();
      } finally {
         System.out.printf(
            "%s printed the document successfully.\n", Thread.currentThread().getName());
         queueLock.unlock();
      }
   }
}

class ThreadDemo extends Thread {
   PrintDemo  printDemo;

   ThreadDemo(String name,  PrintDemo printDemo) {
      super(name);
      this.printDemo = printDemo;
   }   

   @Override
   public void run() {
      System.out.printf(
         "%s starts printing a document\n", Thread.currentThread().getName());
      printDemo.print();
   }
}

public class TestThread {

   public static void main(String args[]) {
      PrintDemo PD = new PrintDemo();

      ThreadDemo t1 = new ThreadDemo("Thread - 1 ", PD);
      ThreadDemo t2 = new ThreadDemo("Thread - 2 ", PD);
      ThreadDemo t3 = new ThreadDemo("Thread - 3 ", PD);
      ThreadDemo t4 = new ThreadDemo("Thread - 4 ", PD);

      t1.start();
      t2.start();
      t3.start();
      t4.start();
   }
}

这将产生以下结果。

输出

Thread - 1  starts printing a document
Thread - 4  starts printing a document
Thread - 3  starts printing a document
Thread - 2  starts printing a document
Thread - 1   Time Taken 4 seconds.
Thread - 1  printed the document successfully.
Thread - 4   Time Taken 3 seconds.
Thread - 4  printed the document successfully.
Thread - 3   Time Taken 5 seconds.
Thread - 3  printed the document successfully.
Thread - 2   Time Taken 4 seconds.
Thread - 2  printed the document successfully.

我们在这里使用ReentrantLock类作为Lock接口的实现。 ReentrantLock类允许线程锁定某个方法,即使该线程已经锁定了其他方法。