我在java中使用ThreadGroups。根据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();
}
现在我无法理解发生了什么,我是新手,为什么我能够获得有关当前线程的线程组的父级的信息。我错过了什么,有关此的任何信息吗?
答案 0 :(得分:1)
我相信文档打算说的是在线程accesses it's own ThreadGroup
时没有安全检查,即它不能以SecurityException
失败:
public final ThreadGroup getThreadGroup() {
return group;
}
但是在ThreadGroup的accessing the parent时会进行安全检查,即它可能会因SecurityException
而失败:
public final ThreadGroup getParent() {
if (parent != null)
parent.checkAccess();
return parent;
}
默认的SecurityManager仅在尝试访问根线程组(默认线程组)时才会检查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
}
}
但是您可以install your own安全管理器覆盖checkAccess(ThreadGroup g)方法。