thread, looper, handler vs ScheduledExecutorService

1) what is looper, 

 A Class used to run a message loop on a messageQueue for a thread, BUT , it is essentially itsself a thread,  think otherwise how it is able to do the loop work. 

Check the source code of Looper, you will find it.


2) A clean thread has a messageQueue natively, while it doesn't have a looper natively, need the developer explicitly create a instance of Looper for a thread.

   An Activity is a thread , with a default Looper already created by default ,so that user save doing that .

   So  a thread with a looper , actually has 2 threads.  And a thread with a handler can work properly only when there is a looper with it, so has 2 threads.


3) Handler is 

   a) a tool that used to send or be sent messages or Runnable Objects to the messageQueue of the thread that host it.

       !!!!looper is used to pickup the messages or Runnable Objects in the messageQueue, and dispatch them to the right handlers.

     thread is a thread, looper is a thread, while handler is not a thread.

   b) has the ability to process some messages by implementing HandleMessage,

=========================

There are two main uses for a Handler: 

(1) to schedule messages and runnables to be executed as some point in the future; and  ----- send/post message/runnables on its own thread.

(2) to enqueue an action to be performed on a different thread than your own.----different thread.

From one perspective:

As you can see, Handler combined thread/looper is able to post a runnable on both  the thread hosting it and a new thread


ScheduledExecutorService create a new thread, and post a runnable to it to be excuted. 

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

scheduler.schedule(launchWelcomeActivityRunnable,2, TimeUnit.SECONDS);


From another perspective:

Handler, message queue, looper combination can be used communication between 2 threads.

ScheduledExecutorService only create a new thread to be excuted. It can not communicate between threads until handler/looper is created for them.





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值