java.util.concurrent.locks.lock
接口用作线程同步机制,类似于同步块。新的锁定机制更灵活,提供比同步块更多的选项。 锁和同步块之间的主要区别如下:
lock
接口处理它。lock
接口提供了这样的选项。lock
接口的方法lock()
和unlock()
可以以不同的方式调用。以下是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
类允许线程锁定方法,即使它已经具有其他方法锁。