美文网首页
【Android】HandlerThread

【Android】HandlerThread

作者: 代码充电宝 | 来源:发表于2020-01-08 16:17 被阅读0次

(1)简单使用

  • HandlerThread用来做队列同步执行
public class AsyncHandler {

    private static final HandlerThread sHandlerThread = new HandlerThread("AsyncHandler");
    private static final Handler sHandler;

    static {
        sHandlerThread.start();
        sHandler = new Handler(sHandlerThread.getLooper());
    }

    public static void post(Runnable r) {
        sHandler.post(r);
    }

    private AsyncHandler() {
    }
}
  • 测试代码
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private Button btn;

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

        btn = ((Button) findViewById(R.id.btn));
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            String name = Thread.currentThread().getName();
            Log.e(TAG, "start: "+name);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 此处是子线程不能刷新UI控件
//            btn.setText("aaaa");
            Log.e(TAG, "end: "+name);
        }
    };


    /**
     * 同步执行执行顺序
     *     start: AsyncHandler
     *     end: AsyncHandler
     *     start: AsyncHandler
     *     end: AsyncHandler
     *     start: AsyncHandler
     *     end: AsyncHandler
     */
    public void go(View view) {

        AsyncHandler.post(runnable);
        AsyncHandler.post(runnable);

        new Thread(new Runnable() {
            @Override
            public void run() {
                AsyncHandler.post(runnable);
            }
        }).start();
    }
}

相关文章

网友评论

      本文标题:【Android】HandlerThread

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