Java并发 专题
您的位置:java > Java并发专题 > Java并发Lock接口
Java并发Lock接口
作者:--    发布时间:2019-11-20

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

  • 序列的保证 - 同步块不提供对等待线程进行访问的序列的任何保证,但lock接口处理它。
  • 无超时,如果未授予锁,则同步块没有超时选项。lock接口提供了这样的选项。
  • 单一方法同步块必须完全包含在单个方法中,而lock接口的方法lock()unlock()可以以不同的方式调用。

lock类中的方法

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

编号 方法 描述说明
1 public void lock() 获得锁
2 public void lockinterruptibly() 获取锁定,除非当前线程中断
3 public condition newcondition() 返回绑定到此lock实例的新condition实例
4 public boolean trylock() 只有在调用时才可以获得锁
5 public boolean trylock(long time, timeunit unit) 如果在给定的等待时间内自由,并且当前线程未被中断,则获取该锁。
6 public void unlock() 释放锁

示例

以下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类允许线程锁定方法,即使它已经具有其他方法锁。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册