我正在開發多線程項目。我試圖啓動一個線程,我從某個類調用一些方法。這個方法可能需要很長時間(一些「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'中完成整個代碼。 –