Java Thread checkAccess() 方法



描述

Java Thread checkAccess() 方法用於確定當前執行的執行緒是否有許可權修改此執行緒。

宣告

以下是 java.lang.Thread.checkAccess() 方法的宣告

public final void checkAccess()

引數

返回值

此方法不返回任何值。

異常

SecurityException − 如果當前執行緒不允許訪問此執行緒。

示例:在多執行緒環境中檢查執行緒是否具有訪問許可權

以下示例演示了 Java Thread checkAccess() 方法的用法。在這個程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadClass。在 main 方法中,我們建立了 ThreadClass 的例項。然後使用 currentThread() 方法檢索當前執行緒,並使用 checkAccess() 方法檢查當前執行緒是否具有許可權。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String args[]) {

      new ThreadClass("A");
      Thread t = Thread.currentThread();

      try {
         /* determines if the currently running thread has permission to 
            modify this thread */
         t.checkAccess();
         System.out.println("You have permission to modify");
      }

      /* if the current thread is not allowed to access this thread, then it 
         result in throwing a SecurityException. */
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

class ThreadClass implements Runnable {

   Thread t;
   String str;

   ThreadClass(String str) {

      this.str = str;
      t = new Thread(this);
      
      // this will call run() function
      t.start();    
   }

   public void run() {
      System.out.println("This is run() function");
   }
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

You have permission to modify
This is run() function

示例:在單執行緒環境中檢查執行緒是否具有訪問許可權

以下示例演示了 Java Thread checkAccess() 方法的用法。在這個程式中,我們建立了一個類 ThreadDemo。在 main 方法中,使用 currentThread() 方法檢索當前執行緒,並使用 checkAccess() 方法檢查當前執行緒是否具有許可權。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String args[]) {

      Thread t = Thread.currentThread();

      try {
         /* determines if the currently running thread has permission to 
            modify this thread */
         t.checkAccess();
         System.out.println("You have permission to modify");
      }

      /* if the current thread is not allowed to access this thread, then it 
         result in throwing a SecurityException. */
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

You have permission to modify
java_lang_thread.htm
廣告