我正在使用Java中的线程组。根据Javadoc,
写道允许线程访问有关其自己线程组的信息,但是 不访问有关其线程组的父线程组或 任何其他线程组。
但是,当我实施以下代码工作时,
public static void main(String args[]){
//parent thread group It_Firm
ThreadGroup It_Firm=new ThreadGroup("It_Firm");
//Child thread group web
ThreadGroup web=new ThreadGroup(It_Firm,"webdeveloper");
/*
* A thread entry in child thread group set in which i am trying to call parent's thread group activecount()
* method,as per the docs it will stop me to call for any information from parent's thread group or any other
* thread group but it is not doing it.
*/
Thread th=new Thread(web,new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
Thread ths[]=new Thread[Thread.currentThread().getThreadGroup().getParent().activeCount()];
Thread.currentThread().getThreadGroup().getParent().enumerate(ths);
for(int i=0;i<ths.length;i++){
System.out.println("group name"+ths[i].getThreadGroup().getName()+" : name : "+ths[i].getName());
System.out.println("state"+ths[i].isAlive());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
},"prashank");
th.start();
//some dummy code in parent thread group
Thread th_pthread=new Thread(It_Firm,new Runnable(){
@Override
public void run() {
boolean flag=true;
while(flag){
Scanner sc=new Scanner(System.in);
char ch=sc.nextLine().charAt(0);
if(ch=='N')
flag=false;
}
}
},"abc pvt ltd");
th_pthread.start();
}
现在我不了解发生了什么,我是新手,为什么我能够获取有关当前线程组的父母的信息。我是否缺少任何信息?
我相信文档打算说的是,当线程访问其自己的 ThreadGroup
时,没有安全检查,即不会在 SecurityException
:
public final ThreadGroup getThreadGroup() {
return group;
}
但是,在访问线程组的父时有一个安全检查,即可能会使用SecurityException
:
public final ThreadGroup getParent() {
if (parent != null)
parent.checkAccess();
return parent;
}
默认安全管理器将仅在尝试访问root thread组(默认线程组(时检查modifyThreadGroup
的权限:
public void checkAccess(ThreadGroup g) {
if (g == null) {
throw new NullPointerException("thread group can't be null");
}
if (g == rootGroup) {
checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
} else {
// just return
}
}
但是,您可以安装自己的安全管理器,该管理器可以覆盖CheckAccess(ThreadGroup G(方法。
请参阅Java开发套件中的权限