ReentrantLock 类的 getOwner() 方法返回锁的当前所有者线程。如果不拥有,则返回 null。当不是所有者的线程调用此方法时,返回值反映当前锁状态的 best-effort 近似值。
用法
protected Thread getOwner()
参数
没有传递参数。
返回
所有者,如果不拥有,则为 null
抛出
不会抛出异常。
例子1
//import statement
import java.util.concurrent.locks.*;
class ReentrantLockgetOwnerExample1 {
public static void main (String args[]) throws InterruptedException {
ReentrantLockClass lock = new ReentrantLockClass();
MyThread t1 = new MyThread(lock);
t1.start();
t1.join();
}
}
class MyThread extends Thread {
ReentrantLockClass lock;
MyThread(ReentrantLockClass lock){
this.lock=lock;
}
public void run() {
if ( ! lock.tryLock()) {
System.out.println(this.getName() + ":lock1 owner:" + lock.owner());
}
System.out.println(this.getName() + ":lock1 owner:" + lock.owner());
}
}
class ReentrantLockClass extends ReentrantLock {
String owner() {
Thread t = this.getOwner();
if (t != null) {
return t.getName();
} else {
return "none";
}
}
}
输出:
Thread-0:lock1 owner:Thread-0
例子2
//import statements
import java.util.concurrent.locks.*;
class ReentrantLockgetOwnerExample2 {
public static void main(String args[]) throws InterruptedException {
ReentrantLockClass2 lock1 = new ReentrantLockClass2();
ReentrantLockClass2 lock2 = new ReentrantLockClass2();
MyThread1 thrd1 = new MyThread1(lock1, lock2);
MyThread1 thrd2 = new MyThread1(lock1, lock2);
thrd1.start();
thrd1.join();
thrd2.start();
thrd2.join();
}
}
class MyThread1 extends Thread {
ReentrantLockClass2 lock1;
ReentrantLockClass2 lock2;
MyThread1(ReentrantLockClass2 lock1, ReentrantLockClass2 lock2){
this.lock1=lock1;
this.lock2=lock2;
}
public void run() {
if ( ! lock1.tryLock()) {
lock2.tryLock();
}
System.out.println(this.getName() + ":lock1 owner:" + lock1.owner());
System.out.println(this.getName() + ":lock2 owner:" + lock2.owner());
}
}
class ReentrantLockClass2 extends ReentrantLock {
String owner() {
Thread t = this.getOwner();
if (t != null) {
return t.getName();
} else {
return "none";
}
}
}
输出:
Thread-0:lock1 owner:Thread-0 Thread-0:lock2 owner:none Thread-1:lock1 owner:Thread-0 Thread-1:lock2 owner:Thread-1
相关用法
- Java ReentrantLock getHoldCount()用法及代码示例
- Java ReentrantLock lock()用法及代码示例
- Java ReentrantLock toString()用法及代码示例
- Java ReentrantLock tryLock()用法及代码示例
- Java ReentrantLock isHeldByCurrentThread()用法及代码示例
- Java ReentrantLock isLocked()用法及代码示例
- Java ReentrantLock isFair()用法及代码示例
- Java ReentrantLock hasQueuedThread()用法及代码示例
- Java ReentrantLock hasQueuedThreads()用法及代码示例
- Java ReentrantLock lockInterruptibly()用法及代码示例
- Java Reentrant getQueueLength()用法及代码示例
- Java Reader read(CharBuffer)用法及代码示例
- Java Reader markSupported()用法及代码示例
- Java Reader ready()用法及代码示例
- Java ResolverStyle valueOf()用法及代码示例
- Java ResourceBundle containsKey()用法及代码示例
- Java ResourceBundle getString()用法及代码示例
- Java ResourceBundle getKeys()用法及代码示例
- Java ResourceBundle clearCache()用法及代码示例
- Java Reader close()用法及代码示例
注:本文由纯净天空筛选整理自 Java ReentrantLock getOwner() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。