ThreadGroup
類的activeCount()
方法確定當前執行的執行緒是否具有修改執行緒組的許可權。
語法
public final void checkAccess()
返回
它不會返回任何值。
異常
SecurityException
:如果不允許當前執行緒存取執行緒組,則丟擲此異常。範例
package com.yiibai;
class NewThread extends Thread {
NewThread(String threadname, ThreadGroup tg) {
super(tg, threadname);
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
System.out.println(Thread.currentThread().getName() + " completed executing");
}
}
public class ThreadGroupCkeckAccessExp {
public static void main(String arg[]) throws InterruptedException, SecurityException {
// creating a ThreadGroup
ThreadGroup g1 = new ThreadGroup("Parent thread");
// creating a child ThreadGroup for parent ThreadGroup
ThreadGroup g2 = new ThreadGroup(g1, "child thread");
// creating a thread
NewThread t1 = new NewThread("Thread-1", g1);
t1.start();
// creating another thread
NewThread t2 = new NewThread("Thread-2", g1);
t2.start();
// Check for access permission of current running thread
g1.checkAccess();
System.out.println(g1.getName() + " has access");
g2.checkAccess();
System.out.println(g2.getName() + " has access");
}
}
執行上面範例程式碼,得到以下結果:
Parent thread has access
child thread has access
Thread-1 completed executing
Thread-2 completed executing