gpt4 book ai didi

java - 断线组java api

转载 作者:行者123 更新时间:2023-12-02 11:40:05 25 4
gpt4 key购买 nike

我正在研究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();
}

现在我无法理解发生了什么,我对此很陌生,为什么我能够获取有关当前线程的线程组父级的信息。我是否遗漏了一些东西,有任何相关信息吗?

最佳答案

我相信文档的意思是,当线程 accesses it's own 时,没有安全检查。 ThreadGroup,即它不会因 SecurityException 失败:

public final ThreadGroup getThreadGroup() {
return group;
}

但是当accessing the parent时有安全检查ThreadGroup 的,即它可能会因 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) 的安全管理器方法。

参见Permissions in the Java Development Kit

关于java - 断线组java api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com