gpt4 book ai didi

java - 如何让线程只修改自己

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:32 28 4
gpt4 key购买 nike

interrupt() 的文档中我们有方法:

Throws:
SecurityException - if the current thread cannot modify this thread

source code该方法是这样的:

public void interrupt() {
if (this != Thread.currentThread())
checkAccess(); //checking access
//The rest is ommited
}

checkAccess 方法依次实现如下:

public final void checkAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkAccess(this);
}
}

默认情况下,据我所知,任何线程都可以修改任何其他线程。

但是有没有办法在 java.policy 文件中指定 modifyThread 权限以允许线程仅修改自身?

java.policy 中,我可以找到唯一的 grant{ ... } 部分。有没有办法拒绝这样的线程通信?

最佳答案

为了让您使用policy files控制谁可以调用 Thread.interrupt() 需要一个 policy在规范这种访问的地方。如您所见,Thread.interrupt() 中没有 SecurityManager.checkPermission() 调用,因此这显然是不可能的。这是设计使然,因为策略旨在限制代码源的访问,而不是线程(可以从多个源位置执行代码)。如果代码源未被授予对特定策略的访问权限,它永远不能运行受该策略保护的代码。

相反,Thread 访问由 SecurityManager.checkAccess(Thread) 控制方法。来自 Thread.checkAccess() :

Determines if the currently running thread has permission to modify this thread.

If there is a security manager, its checkAccess method is called with this thread as its argument.

SecurityManager.checkAccess(Thread) 准确描述了如何限制访问:

Throws a SecurityException if the calling thread is not allowed to modify the thread argument.

This method is invoked for the current security manager by the stop, suspend, resume, setPriority, setName, and setDaemon methods of class Thread. [sic. this should include interrupt as well]

.... If the thread argument is not a system thread, this method just returns silently.

Applications that want a stricter policy should override this method....

就这样吧。定义一个自定义 SecurityManager,它在 checkAccess(Thread) 中引发异常以限制谁可以中断或以其他方式修改线程。


关于授予与拒绝权限的第二个问题,Policy File Syntax页面详细信息,只有 grant 语句,there is no deny mechanism .

关于java - 如何让线程只修改自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804736/

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