handler 的post方法解惑

我们在子线程使用handler的post方法时,如下:

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("UI线程ID2="+Thread.currentThread().getId());
        hh.post(new Runnable() {
            @Override
            public void run() {
             textView2.setText("gaibianle");
                System.out.println("UI线程ID3="+Thread.currentThread().getId());
            }
        }) ;
    }
}

).start();
post方法里面传入 new Runnable 对象,然后在其下面的run方法中,竟然可以操作UI线程,更改ui,对此不少人有疑惑,不是不能在非UI线程更改UI吗?

答案如下:我们传入的new Runnable ,不是新的线程。而是UI线程。

我们在代码中打印当前的线程:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    textView2= (TextView) findViewById(R.id.texthh);
    System.out.println("UI线程ID1="+Thread.currentThread().getId());
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("UI线程ID2="+Thread.currentThread().getId());
            hh.post(new Runnable() {
                @Override
                public void run() {
                 textView2.setText("gaibianle");
                    System.out.println("UI线程ID3="+Thread.currentThread().getId());
                }
            }) ;
        }
    }

    ).start();
结果如下:

08-07 22:09:41.673 30533-30533/com.example.cirleimg I/System.out: UI线程ID1=1
08-07 22:09:41.676 30533-30664/com.example.cirleimg I/System.out: UI线程ID2=25480
08-07 22:09:41.743 30533-30533/com.example.cirleimg I/System.out: UI线程ID3=1

所以,handler的Post方法就是直接操作UI线程。


参考:http://www.bkjia.com/Androidjc/893143.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值