美文网首页
非主线程更新UI:Activity.runOnUiThread(

非主线程更新UI:Activity.runOnUiThread(

作者: 万杰高科 | 来源:发表于2017-08-10 14:21 被阅读0次

练习心得

  • runOnUiThread是Activity的方法,其中的run方法会在UI线程中执行,如果是在主线程中调用则立即执行,如果是在异步线程中则将其放入Activity的EventQueue中
  • 用volatile修饰的变量如private static volatile int a = 2;是为解决多线程访问统一变量时的可见性问题(可见性:即保障每个线程获取的变量值都是最新的一致的,线程同步要解决的3个问题‘原子性’、‘可见性’、‘有序性’)

代码样例

/**
 * Created by Rambo 
 */

public class MyActivity extends MainActivity {

    private EditText myEditText = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        myEditText = (EditText) findViewById(R.id.myEditText);

        Thread otherThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.v(TAG, "otherThread2:" + Thread.currentThread().getName());
                for (int index = 0; index < 5; index++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 匿名内部类所引用的方法的局部变量要求是final的,是为防止内部类实例的生命周期大于局部变量的情况
                    // 定义为final后局部变量的生命周期等同域外部类变量
                    final int finalIndex = index;
                    /**
                     * activity的方法,其中的run方法会在UI线程中执行,如果是在主线程中调用则
                     * 立即执行,如果是在异步线程中则将其放入Activity的EventQueue中
                     */
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.v(TAG, "runOnUiThread:" + Thread.currentThread().getName());
                            myEditText.setText(Integer.toString(finalIndex));
                        }
                    });
                }

            }
        });
        otherThread.start();
    }

}

执行Log日志如下:

运行日志

相关文章

网友评论

      本文标题:非主线程更新UI:Activity.runOnUiThread(

      本文链接:https://www.haomeiwen.com/subject/zadhrxtx.html