Android多线程使用详解

2017-08-10  本文已影响0人  kjy_112233

一、Thread、HandlerThread

    private class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
        }
    }

    private Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            
        }
    });

    //启动子线程
    MyThread myThread = new MyThread();
    myThread.start();
    private void initHandlerThread() {
        //创建HandlerThread实例
        HandlerThread handlerThread = new HandlerThread("handler_thread");
        //开始运行线程
        handlerThread.start();
        //获取HandlerThread线程中的Looper实例
        Looper loop = handlerThread.getLooper();
        //创建Handler与该线程绑定。
        Handler handler = new Handler(loop) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //执行子线程任务
            }
        };
    }

二、AsyncTask

    private class MyAsyncTask extends AsyncTask{
        //执行线程任务前的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //接收输入参数
        //在方法中执行任务中的耗时操作
        //返回线程任务执行的结果
        @Override
        protected Object doInBackground(Object[] objects) {
            return null;
        }

        //在主线程显示线程任务执行的进度
        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
        }

        //接收线程任务执行结果
        //将执行结果显示到UI组件
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
        }

        //取消异步任务
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    MyAsyncTask myAsyncTask = new MyAsyncTask();
    myAsyncTask.execute();
    myAsyncTask.cancel(true);

优点:

三、Activity.runOnUiThread

    private Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //更新UI操作
                }
            });
        }
    });

Activity.runOnUiThread源码

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
上一篇下一篇

猜你喜欢

热点阅读