在 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
, andsetDaemon
methods of class Thread. [sic. this should includeinterrupt
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/