我正在开发多线程项目。我试图启动一个线程,我从某个类调用一些方法。这个方法可能需要很长时间(一些“while”循环,我没有控制),所以我会强制退出该循环来结束线程。但我会使用线程类的方法(而不是java.lang.Thread,但他的儿子)来做到这一点。我知道如何在C/C++(通过引用传递SomeClass.SomeMethod的参数),但在Java中我不能(我认为)。修改参数的值
public class A extends Thread {
boolean isThreadClosing = false;
@Override
void run () {
// if it was C/C++ i can pass the arguments by reference
SomeClass.SomeMethod (isThreadClosing);
}
void stopThread () {
isThreadClosing = true;
}
}
public class SomeClass {
void SomeMethod (boolean isThreadClosing) {
while (!isThreadClosing) {
// do...
}
}
}
所以,问题是我怎么能具体化的方法SomeClass.SomeMethod(...)的参数值,从线程的类?
这里有一个解决方案,但我不喜欢,因为我不得不把线程的类传递给methood。
public class A extends Thread {
boolean isThreadClosing = false;
@Override
void run () {
// if it was C/C++ i can pass the arguments by reference
SomeClass.SomeMethod (this);
}
void stopThread () {
isThreadClosing = true;
}
boolean isClosing () {
return isThreadClosing;
}
}
public class SomeClass {
void SomeMethod (A thread) {
while (!thread.isClosing ()) {
// do...
}
}
}
检查性病标志'interrupted'代替'isClosing' – Val
除非我记错了,你试图达到的目标不会工作,因为你所在的“循环”不会因为“isThreadClosing”的值被改变而停止,所以一旦“循环”中的工作是“isThreadClosing”开始。那将是你得到你评论的地方// do ..通过这一点,所做的工作不会停止,因为'isThreadClosing'发生了变化,它会在'while'中完成整个代码。 –