如何将变量从线程传递到外部环境?

Loo*_*ear 5 variables multithreading android

我有一个嵌套在主要活动中的线程:

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    new Thread(new Runnable(){
        public void run() {
            int myInt = 1;
            // Code below works fine and shows me myInt
            TextView textView = (TextView) findViewById(R.id.text_view);
            textView.setText(myInt);
        }
    }).start();

    // Code below doesn't work at all
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(myInt);

}
Run Code Online (Sandbox Code Playgroud)

我不确定这个结构是否正确。我应该如何将myInt变量传递给ThreadMainActivity以便它在 Thread 之外变得可识别和可操作?

den*_*rew 1

在尝试设置线程外部(在主线程上)的文本视图之前,您首先需要一个已设置的整数的全局变量。它需要提前设置,因为您启动的新线程将简单地启动并移动到下一行代码,因此 myInt 尚未设置。

然后,至少在最初,在主线程上使用预定的全局整数值作为文本视图。如果您想在启动的线程中更改它,请在您的类中创建一个方法,例如 setIntValue() ,它将从线程传入整数并将全局变量设置为该值。如果您愿意,我可以稍后更新代码示例。

更新:示例代码

public class MainActivity extends Activity {

//your global int
int myInt

public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);

new Thread(new Runnable(){
    public void run() {
        int myRunnableInt = 1;
        // Code below works fine and shows me myInt
        TextView textView = (TextView) findViewById(R.id.text_view);
        textView.setText(String.valueOf(myRunnableInt));

        //say you modified myRunnableInt and want the global int to reflect that...
        setMyInt(myRunnableInt);
    }
}).start();

//go ahead and initialize the global one here because you can't directly access your
myRunnableInt
myInt = 1;

TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(myInt)); //now you will have a value here to use

//method to set the global int value
private void setMyInt(int value){
    myInt = value;

    //you could also reset the textview here with the new value if you'd like
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(String.valueOf(myInt));
}
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您只希望能够重置文本视图,而不是拥有一个全局的可操作变量,我建议更改方法以仅传递新整数并设置文本视图,而不是存储全局变量,例如这:

private void setTextView(int newInt){
    TextView textView = (TextView) findViewById(R.id.text_view);
    textView.setText(String.valueOf(newInt));
}
Run Code Online (Sandbox Code Playgroud)

如果执行上述操作,请确保当您从线程内调用该方法时,在 UI 线程上调用它,如下所示: runOnUiThread(new Runnable()){ public void run(){ //update UI elements } }