Java 如何使自定义线程不可被任何其他线程修改?
} 输出:Java 如何使自定义线程不可被任何其他线程修改?,java,multithreading,Java,Multithreading,} 输出: class MySecurityManager extends SecurityManager{ public void checkAccess(Thread t) { super.checkAccess(t); if (t==Thread.currentThread()) { return; // thread always can modify itself } if (t instanceof
class MySecurityManager extends SecurityManager{
public void checkAccess(Thread t) {
super.checkAccess(t);
if (t==Thread.currentThread()) {
return; // thread always can modify itself
}
if (t instanceof AThread) {
throw new SecurityException();
}
}
}
1.根据Alexei的输入,这是我尝试过的。我是否正确地实施了它
2.你能解释一下我在main()中创建AThread对象时引发异常的原因吗
3.我没有修改AThread,但仍然抛出异常为什么
4.我是否已放置System.setSecurityManager(新的MySecurityManager());在正确的位置基本上,您必须声明自己的SecurityManager:
In BThread()
Thread[main,5,main]
Thread-0
This is B run() function
Thread[Bth,5,main]
Exception in thread "main" java.lang.SecurityException
并安装它:
class MySecurityManager extends SecurityManager{
public void checkAccess(Thread t) {
super.checkAccess(t);
if (t.getId()==0) {// a hack to determine if we are in thread's constructor
return;
}
if (t==Thread.currentThread()) {
return; // thread always can modify itself
}
if (t is non-modifiable) {
throw new SecurityException();
}
}
现在如何确定t是否不可修改?这取决于你。可能在您的项目中已经有一些属性将线程描述为不可修改的。如果不是,我建议声明您自己的类nonmodifiablethreadextenstedthread
,并检查t instanceof NonModifiableThread
。另一个选项是创建特殊的线程组,并检查给定的线程是否属于该组
更新
事实证明,线程的构造函数本身调用setriority()
,因此检查访问(this)
。为了允许另一个线程调用构造函数,需要一种方法来确定构造函数是否正在运行。我补充说
System.setSecurityManager(new MySecurityManager());
到checkAccess,因为id是在构造函数末尾分配的。但这并没有记录在案,可以改变。更可靠的解决方案是:
- 仅在创建所有线程后安装security manager,或
- 让MySecurityManager保留所有不可修改线程的集合,而不是检查线程的类。让NonModifiableThread的构造函数在构造函数的安全管理器中注册自己(在超级构造函数完成后),并且NonModifiableThread.run()方法在执行后注销
- (甚至更好)在类NonModifiableThread中声明一个布尔变量,该变量在构造函数中更改,以便MySecurityManager可以知道构造函数的执行是否完成
System.setSecurityManager(new MySecurityManager());
if (t.getId()==0) {
return;
}