0

我有一个简单的问题:

我有一个名为 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();
}

不管用...

4

3 回答 3

2

因为可访问的接口来自Thread. 为了让您的方法可以从外部访问,您需要指定一个公开此方法的类型。

如果您仔细看一下,该方法是在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();
    ...
}
于 2012-07-10T09:54:35.300 回答
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();
}
于 2012-07-10T10:06:18.053 回答
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();
}

注意:您也可以阅读这篇文章以获得更深入的版本。

于 2012-07-10T10:58:18.487 回答