The checkAccess()
method of the Thread
class in Java is used to check whether the currently running thread has permission to modify the specified thread.
void checkAccess(Thread thread)
This method accepts only one parameter of the Thread
type.
thread
: This is the thread to be checked.This method does not return any value.
The checkAccess()
method throws the SecurityException
exception if the currently running thread does not have permission to change resources.
In the code snippet below, we have two threads, thread1
and thread2
, named Thread-1
and Thread-2
, respectively. As highlighted, we can use checkAccess()
to check whether this
thread has access to resources or not.
// Load Thread classimport java.lang.Thread;// Main Classpublic class MainThread extends Thread{public void run(){System.out.println(Thread.currentThread().getName()+" execution finished");}// it will also throw exceptionspublic static void main(String arg[]) throws SecurityException, InterruptedException {// Creating the threadsMainThread thread1 = new MainThread();MainThread thread2 = new MainThread();// Start thread1thread1.start();thread1.setName("Thread-1");// Start thread2thread2.start();thread1.setName("Thread-2");// check for this threadthread1.checkAccess();System.out.println(thread1.getName() + " has access");thread2.checkAccess();System.out.println(thread2.getName() + " has access");}}