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

标签 java multithreading

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/

相关文章:

swift - 获取 NSManagedObject 实例的上下文是线程安全的吗?

java - 为什么 maven-jlink-plugin 会崩溃?什么是非法论点?

ios - 使用 dispatch_async() 避免 View 阻塞的解决方法是什么

java - 如何在android中调整位图图像对比度?

java - 需要将第一个对象的字段复制到第二个对象中

c - __sync_bool_compare_and_swap 不工作

c - 如何在 Linux 中记录多线程进程的线程堆栈

Java线程连接()

java - 如何改进这个java代码 - 将字节数组转换为int

java - 如何在包含许多参数的字符串中设计 String decollat​​or