Android基础学习之异步任务使用Thread(线程)

线程是处理异步任务最常用的方法,下面演示使用线程去更新UI线程的方法使用。

示例:

public class TestThreadActivity extends Activity{
    private TextView t1;
    private Button btn1;
    private Button btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        t1=(TextView)findViewById(R.id.textView1);
        btn1 = (Button) findViewById(R.id.button1);
        btn2 = (Button) findViewById(R.id.button2);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            test1(); //演示1,主要使用了UI线程的runOnUiThread方法
            break;
        case R.id.button2:
            test2(); //演示2,主要使用操作对象的postDelayed(Runnable, long)方法
            break;

        default:
            break;
        }
    }

    //处理线程问题的方法,可以runnable对象"看成是"子线程运行的代码
    private void test1() {
        new Thread(new Runnable() {     
            @Override
            public void run() {//子线程运行代码的入口
                try {
                    Thread.sleep(5000); //为了方便观察,休眠5s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                TestThreadActivity.this.runOnUiThread(new Runnable() { //runnable对象
                    //把发送到事件队列
                    @Override
                    public void run() {
                        // 这里可执行UI更新
                        t1.setText("boom,boom,boom......../.");
                    }
                });                             
            }
        }).start(); 
    }

    private void test2() {
        t1.postDelayed(new Runnable() { 
            @Override
            public void run() {
                Log.e("ql debug", ">>>>"+Thread.currentThread());
                t1.setText("boom,boom,boom......../.");
            }
        }, 5000);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值