我有一个简单的问题:
我有一个名为rlMF的线程。我这样创造了它:
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles();
stopTh();
}
public void stopTh() {
activityStopped = true;
}
});
现在我想从外部线程调用stopTh函数。为什么我不能简单地调用rlMF.stopTh();我还能做什么呢?
示例:
protected void onPause() {
Log.d("Info", "destroying...");
activityStopped = true;
rlMF.stopTh();
super.onPause();
}
不工作......
答案 0 :(得分:2)
因为可访问的界面来自Thread
。为了让您可以从out访问方法,您需要指定一个公开此方法的类型。
如果你仔细看一下这个方法是在Runnable
的实例中实现的。甚至不在Thread
。
如果你真的需要访问Runnable
对象,你可能会有这样的事情:
class MyRunnable implements Runnable {
public void run() {
...
}
public void fooBar() {
...
}
}
public void someMethod() {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
...
myRunnable.fooBar();
...
}
答案 1 :(得分:0)
弗朗西斯科方法的一个例子,除了你想要实现的目标。也许这可以指出你正确的方向
public class CustomRun implements Runnable {
public void run() {
reloadMissingFiles();
stopTh();
}
public void stopTh() {
activityStopped = true;
}
}
在您的代码中
// start thread with custom runner
CustomRun runner = new CustomRun();
new Thread(runner).start();
// call your stopTh method on CustomRun class
protected void onPause() {
Log.d("Info", "destroying...");
activityStopped = true;
runner.stopTh();
super.onPause();
}
答案 2 :(得分:0)
您的目标是从onPause
中断线程。有几种方法可以做到这一点,但实际上,您需要在reloadMissingFiles
中包含一些可中断性。
选项1
您可以使用类似的布尔标志 - 您需要将其声明为volatile
以确保更改在线程中可见:
private volatile boolean activityStopped = false;
public void reloadMissingFiles() {
while (!activityStopped) {
//load small chunks so that the activityStopped flag is checked regularly
}
}
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles(); //will exit soon after activityStopped has been set to false
}
});
protected void onPause() {
//This will stop the thread fairly soon if the while loop in
//reloadMissingFiles is fast enough
activityStopped = true;
super.onPause();
}
选项2(更好的方法)
我不知道你在reloadMissingFiles
做了什么,但我想这是某种I / O操作,通常是可以中断的。然后,您可以制定中断策略,一旦捕获到InterruptedException,就会停止:
public void reloadMissingFiles() {
try {
//use I/O methods that can be interrupted
} catch (InterruptedException e) {
//cleanup specific stuff (for example undo the operation you started
//if you don't have time to complete it
//then let the finally block clean the mess
} finally {
//cleanup (close the files, database connection or whatever needs to be cleaned
}
}
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles(); //will exit when interrupted
}
});
protected void onPause() {
runner.interrupt(); //sends an interruption signal to the I/O operations
super.onPause();
}
注意:您还可以阅读this article以获取更深入的版本。