|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "HandlerThread" |
| 4 | +date: 2019-06-24 |
| 5 | +categories: ["Background"] |
| 6 | +image: background/handlerthread |
| 7 | +github: background/tree/master/handlerthread |
| 8 | +description: "Background threading" |
| 9 | +keywords: "thread, handler, handlerthread, looper, threadpool, executor, runnable, callable, future, async, task, background, threading, android, programowanie, programming" |
| 10 | +--- |
| 11 | + |
| 12 | +## Thread |
| 13 | +Klasa `Thread` w `Java` reprezentuje wątek wykonania programu i jest podstawą wielu implementacji mechanizmów wielowątkowości. Pozwala na wykonanie pracy na innym wątku. W czystej implementacji bez wsparcia innych klas może służyć do wykonywania długich zadań bez komunikacji z wątkiem głównym. Wątek działa niezależnie od cyklu zycia aplikacji, dlatego potrafia przetrwać zmianę konfiguracji czy wyjście z aplikacji (trafia do póli wątków). Zatrzymanie działania następuje automatycznie po zakończeniu pracy lub w sposób manualny (metodą `interrupt`). Może być tylko raz wykonany zatem każde uruchomienie oczekiwanej pracy wymaga nowej instancji co sprawia, że nie nadaje sie do ponownego użytku. Komunikacja z wątkiem głównym może przebiegać przy użyciu klasy `Handler`. |
| 14 | + |
| 15 | +{% highlight kotlin %} |
| 16 | +class ThreadActivity : AppCompatActivity() { |
| 17 | + |
| 18 | + val runnable = Runnable { |
| 19 | + //some background job |
| 20 | + runOnUiThread { |
| 21 | + //UI job if needed |
| 22 | + } |
| 23 | + } |
| 24 | + val thread = Thread(runnable) //pass runnable or create anonymous object |
| 25 | + |
| 26 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 27 | + super.onCreate(savedInstanceState) |
| 28 | + setContentView(R.layout.activity_thread) |
| 29 | + |
| 30 | + button.setOnClickListener { |
| 31 | + //do not allow start thread if is started |
| 32 | + if(thread.state == Thread.State.NEW) |
| 33 | + thread.start() |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + override fun onDestroy() { |
| 38 | + super.onDestroy() |
| 39 | + if(thread.state != Thread.State.TERMINATED) |
| 40 | + thread.interrupt() //stop the thread if needed |
| 41 | + } |
| 42 | +} |
| 43 | +{% endhighlight %} |
| 44 | + |
| 45 | +## Looper |
| 46 | +Mówiąc o wątkach w Android nie sposób nie wspomnieć o klasie `Looper`, która używana jest do uruchamiania pętli wiadomości dla wątku. Wspiera wykonanie pracy wątku przez dostarczanie wybranych wiadomości i zadań z kolejki do odpowiednich obiektów klasy `Handler`. Każdy wątek `Thread` może mieć jedną uniknalną instancje `Looper`. |
| 47 | + |
| 48 | +## Handler |
| 49 | +`Handler` umożliwia komunikacje między wątkami poprzez wykorzystanie kanału wiadomości. Jest pośrednio powiązany z wątkiem `Thread` poprzez bezpośrednie przekazanie obiektu `Looper` danego wątku w konstruktorze (domyślnie jest to `Looper` wątku w którym `Handler` jest tworzony). Działa więc na wątku, który jest właścicielem dostarczonej instancji `Looper`. Wiadomość `Message` może być wysyłana z dowolnego miejsca przez `sendMessage` oraz zostać odebrana przez `handleMessage` na wątku obiektu `Handler`. Natomiast zadanie `Runnable` wywoływane jest metodą post, a jego wykonanie odbywa się na wątku obiektu `Handler`. |
| 50 | + |
| 51 | +{% highlight kotlin %} |
| 52 | +class HandlerActivity : AppCompatActivity() { |
| 53 | + |
| 54 | + val START = 1 |
| 55 | + val FINISH = 2 |
| 56 | + |
| 57 | + val runnable = Runnable { |
| 58 | + //some background job |
| 59 | + handler.sendMessage(createMessage(FINISH, "result")) //send message to handle action |
| 60 | + handler.post { |
| 61 | + //do action on UI without message communication |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + val thread: Thread = Thread(runnable) |
| 66 | + |
| 67 | + val handler = object: Handler(Looper.getMainLooper()) { //pass Looper of thread owner |
| 68 | + override fun handleMessage(msg: Message?) { |
| 69 | + super.handleMessage(msg) |
| 70 | + if(msg?.what == START && thread.state == Thread.State.NEW) { |
| 71 | + thread.start() |
| 72 | + } |
| 73 | + else if(msg?.what == FINISH) { |
| 74 | + //some action with msj.obj result |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + fun createMessage(what : Int, obj : Any) : Message { |
| 80 | + val message = Message() |
| 81 | + message.what = what |
| 82 | + message.obj = obj |
| 83 | + return message |
| 84 | + } |
| 85 | + |
| 86 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 87 | + super.onCreate(savedInstanceState) |
| 88 | + setContentView(R.layout.activity_handler) |
| 89 | + |
| 90 | + button.setOnClickListener { |
| 91 | + //instead of direct thread.start() it can be done by sending message |
| 92 | + handler.sendEmptyMessage(START) |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + override fun onDestroy() { |
| 97 | + super.onDestroy() |
| 98 | + handler.removeCallbacksAndMessages(null) //remove pending work from MessageQueue |
| 99 | + thread.interrupt() |
| 100 | + } |
| 101 | +} |
| 102 | +{% endhighlight %} |
| 103 | + |
| 104 | +## HandlerThread |
| 105 | +`HandlerThread` jest rozbudowaną klasą `Thread`, która posiada własną instancję `Looper` i `Handler` dzięki czemu potrafi kolejkować zadania i może być użyty wielokrotnie. Zadania wykonywane są synchronicznie w sposób sekwencyjny. Obiekt `HandlerThread` podobnie jak Thread jest aktywny dopóki nie zostanie zniszczony automatycznie przez system lub ręcznie. |
| 106 | + |
| 107 | +{% highlight kotlin %} |
| 108 | +class HandlerThreadActivity : AppCompatActivity() { |
| 109 | + |
| 110 | + //work to do by requestHandler |
| 111 | + val runnable = Runnable { |
| 112 | + //some background job |
| 113 | + responseHandler.sendMessage(Message()) //send message or post the job |
| 114 | + responseHandler.post { |
| 115 | + //some UI action |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + //handler on the main thread, override handleMessage if needed |
| 120 | + val responseHandler = object: Handler(Looper.getMainLooper()) { |
| 121 | + override fun handleMessage(msg: Message?) { |
| 122 | + super.handleMessage(msg) |
| 123 | + //some action on UI |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + //handler on the background thread of handlerThread object |
| 128 | + lateinit var requestHandler: Handler |
| 129 | + |
| 130 | + //instead of Thread use reusable HandlerThread |
| 131 | + //this can be also done by extend HandlerThread class and putting there Handler object |
| 132 | + val handlerThread = HandlerThread("HandlerThread") |
| 133 | + |
| 134 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 135 | + super.onCreate(savedInstanceState) |
| 136 | + setContentView(R.layout.activity_handler_thread) |
| 137 | + |
| 138 | + handlerThread.start() //start the thread |
| 139 | + requestHandler = Handler(handlerThread.looper) //now Looper of handlerThread can be passed |
| 140 | + |
| 141 | + button.setOnClickListener { |
| 142 | + requestHandler.post(runnable) //post the job to MessageQueue |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + override fun onDestroy() { |
| 147 | + super.onDestroy() |
| 148 | + //remove tasks and messages from handlers |
| 149 | + requestHandler.removeCallbacksAndMessages(null) |
| 150 | + responseHandler.removeCallbacksAndMessages(null) |
| 151 | + handlerThread.quitSafely() //quit HandlerThread's Looper |
| 152 | + handlerThread.interrupt() //stop current job |
| 153 | + } |
| 154 | +} |
| 155 | +{% endhighlight %} |
| 156 | + |
| 157 | +## Pula wątków |
| 158 | +Pula wątków (`ThreadPoolExecutor`) jest pojedynczą kolejką typu `FIFO` składającą się z grupy wątków roboczych, które w momencie osiągnięcia stanu dostępności pobierają zadanie z kolejki. Umożliwia asynchroniczne wykonanie zadań przy zachowaniu optymalnej strategii przetwarzania wielowątkowoego, dostarcza mechanizm zarządzania wątkami (dodawanie, anulowanie, priorytety) oraz prostą statystykę. Pula wątków może być użyta przez jedną z implementacji interfejsu `Executor`, `Callable` czy `Future`. Przeważnie instancje uzyskuje się przy pomocy metody wytwórczej z klasy `Executors` oferującej kilka rodzajów typu puli watków. |
| 159 | + |
| 160 | +{% highlight kotlin %} |
| 161 | +class ThreadPoolActivity : AppCompatActivity() { |
| 162 | + |
| 163 | + //this ExecutorService is wrapped ThreadPoolExecutor (this class extends ExecutorService) |
| 164 | + //equivalent of ThreadPoolExecutor with min and max only 1 thread in pool and LinkedBlockingQueue |
| 165 | + val executor : ExecutorService = Executors.newSingleThreadExecutor() |
| 166 | + |
| 167 | + val runnable = Runnable { |
| 168 | + //some background job |
| 169 | + uiHandler.post { |
| 170 | + //some UI job |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + val callable = Callable { |
| 175 | + //some background job and return result |
| 176 | + return@Callable "result" |
| 177 | + } |
| 178 | + |
| 179 | + val uiHandler = Handler() |
| 180 | + |
| 181 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 182 | + super.onCreate(savedInstanceState) |
| 183 | + setContentView(R.layout.activity_thread_pool) |
| 184 | + |
| 185 | + button1.setOnClickListener { |
| 186 | + //use executor with Runnable |
| 187 | + executor.execute(runnable) |
| 188 | + } |
| 189 | + |
| 190 | + button2.setOnClickListener { |
| 191 | + //use executor with Callable |
| 192 | + val future : Future<String> = executor.submit(callable) |
| 193 | + val result = future.get() |
| 194 | + //this can be canceled by run future.cancel() |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + override fun onDestroy() { |
| 199 | + super.onDestroy() |
| 200 | + //remove tasks and messages from handlers |
| 201 | + uiHandler.removeCallbacksAndMessages(null) |
| 202 | + executor.shutdownNow() //kill all threads |
| 203 | + } |
| 204 | +} |
| 205 | +{% endhighlight %} |
0 commit comments