new Runnable() but no new thread?

前端 未结 8 2191
名媛妹妹
名媛妹妹 2020-12-08 11:11

I\'m trying to understand the code here , specifically the anonymous class

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
   final l         


        
8条回答
  •  忘掉有多难
    2020-12-08 11:42

    Shouldn't creating a new Runnable class make a new second thread?

    No. new Runnable does not create second Thread.

    What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?

    Runnable is posted to Handler. This task runs in the thread, which is associated with Handler.

    If Handler is associated with UI Thread, Runnable runs in UI Thread.

    If Handler is associated with other HandlerThread, Runnable runs in HandlerThread


    To explicitly associate Handler to your MainThread ( UI Thread), write below code.

    Handler  mHandler = new Handler(Looper.getMainLooper();
    

    If you write is as below, it uses HandlerThread Looper.

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler requestHandler = new Handler(handlerThread.getLooper());
    

提交回复
热议问题