我正在开发多线程项目。我正在尝试启动一个线程,在其中调用某个类中的某个方法。此方法可能需要很长时间(一些我无法控制的“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(...) 的参数值?
这里有一个解决方案,但我不喜欢,因为我必须将线程的类传递给方法。
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...
}
}
}
最佳答案
我会使用一个简单的 AtomicBoolean 作为 while 语句的条件来完成此操作。
给定一个线程类:
public class ThreadA extends Thread {
private AtomicBoolean stop = new AtomicBoolean(false);
public void run(){
someClass.someMethod(stop);
}
public void stopProcessing(){
stop.set(true);
}
}
public class SomeClass {
public void someMethod(AtomicBoolean stop){
while(!stop.get()){
...
}
}
}
这意味着通过以下方式与线程交互:
ThreadA thread = new ThreadA();
thread.start();
...
thread.stopProcessing();
关于java - 修改参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20570649/