How to initialize a Thread in Kotlin?

后端 未结 9 2261
青春惊慌失措
青春惊慌失措 2021-02-06 21:14

In Java it works by accepting an object which implements runnable :

Thread myThread = new Thread(new myRunnable())

where myRunnable

相关标签:
9条回答
  • 2021-02-06 22:09
    fun main(args: Array<String>) {
    
        Thread({
            println("test1")
            Thread.sleep(1000)
        }).start()
    
        val thread = object: Thread(){
            override fun run(){
                println("test2")
                Thread.sleep(2000)
            }
        }
    
        thread.start()
    
        Thread.sleep(5000)
    }
    
    0 讨论(0)
  • 2021-02-06 22:12

    Firstly, create a function for set default propery

    fun thread(
      start: Boolean = true, 
      isDaemon: Boolean = false, 
      contextClassLoader: ClassLoader? = null, 
      name: String? = null, 
      priority: Int = -1, 
      block: () -> Unit
    ): Thread
    

    then perform background operation calling this function

    thread(start = true) {
         //Do background tasks...
    }
    

    Or kotlin coroutines also can be used to perform background task

    GlobalScope.launch {
    
        //TODO("do background task...")
        withContext(Dispatchers.Main) {
            // TODO("Update UI")
        }
        //TODO("do background task...")
    }
    
    0 讨论(0)
  • 2021-02-06 22:12
    thread { /* your code here */ }
    
    0 讨论(0)
提交回复
热议问题