多线程的使用

多线程实现方式

  • Thread
  • Handler + Runnable
  • IntentService
  • AsyncTask
  • ThreadPoolExecutor

优缺点比较
Thread


image.png

image.png

Handler+Runnable

......
        runnable.run()
        runnable2.run()
        runnable3.run()
        runnable4.run()


......
   val runnable = Runnable { LogUtils.e("runnable1")
        sleep(3000)
    }

    val runnable2 =  Runnable{ LogUtils.e("runnable2") }

    val runnable3 = Runnable { LogUtils.e("runnable3") }

    val runnable4 = Runnable { LogUtils.e("runnable4") }
image.png

AsyncTask

......
        task3().execute()
        task4().execute()
        task1().execute()
        task2().execute()
......
class task1() : AsyncTask(){
        override fun doInBackground(vararg params: Void?): String {
            LogUtils.e("task1")
            sleep(3000)
            return ""
        }
    }

    class task2() : AsyncTask(){
        override fun doInBackground(vararg params: Void?): String {
            LogUtils.e("task2")
            return ""
        }
    }

    class task3() : AsyncTask(){
        override fun doInBackground(vararg params: Void?): String {
            LogUtils.e("task3")
            return ""
        }
    }

    class task4() : AsyncTask(){
        override fun doInBackground(vararg params: Void?): String {
            LogUtils.e("task4")
            return ""
        }
    }

----------------------------------------------------------------------------------------------------
2021-03-31 14:03:40.756 19140-19177/com.polycents.scannernow E/日常打log: task3
2021-03-31 14:03:40.757 19140-19178/com.polycents.scannernow E/日常打log: task4
2021-03-31 14:03:40.757 19140-19177/com.polycents.scannernow E/日常打log: task1
2021-03-31 14:03:43.798 19140-19200/com.polycents.scannernow E/日常打log: task2
image.png

你可能感兴趣的:(多线程的使用)