當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java ReentrantLock getOwner()用法及代碼示例


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 getOwner() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。