Android——后台线程

文章目录


线程池

//创建固定数量的线程池
ExecutorService executors = Executors.newFixedThreadPool(4);
//简单使用:executors.execute传入Runnable即可
for (int i = 0; i < 5; i++) {
    int finalI = i;
    executors.execute(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(finalI * 1000 + 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "run: thread id" + Thread.currentThread().getId());
        }
    });
}


AsyncTask

//继承AsyncTask并重写相应方法
/**
 * Params:
 *      Params 传入的参数(可变参数:array)
 *      Progress 类中传递进度的类型 (可变参数:array)
 *      Result 处理完成由doInBackground返回的结果类型
 */
class MyAsyncTask extends AsyncTask<String,Integer,String>{
    ProgressBar progressBar;
    TextView textView;


    //此方法在主线程中执行,可以在此获得组件引用,进行UI设置
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar = findViewById(R.id.pb_show);
        progressBar.setProgress(0);
        textView = findViewById(R.id.tv_show);
        textView.setText("processing");
    }

    //此方法在子线程中执行
    @Override
    protected String doInBackground(String... strings) {
        int current = 0;
        for (String string : strings) {
            try {
                Thread.sleep(200);
                Log.d(TAG, "doInBackground: " + string);
                current += 10;
                publishProgress(current);//更新进度,在onProgressUpdate更新UI
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        return "successfully";
    }

    //返回处理结果,在主线程中执行
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        textView.setText(s);
        Log.d(TAG, "onPostExecute: " + Thread.currentThread().getName());
    }

    //处理进度改变,在主线程中执行
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }


}

//在Activity中new实例并且开始执行任务
String[] strings = new String[10];
for (int i = 0; i < 10; i++) {
    strings[i] = "string_" + i;
}
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(strings);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值