怎样使用多线程

  • 继承thread,复写runnable
  • 直接复写runnable,传入Thread
  • callable 和FutureTask

callable 和 FutureTask

callable例子

fun runAction3(){
        var executor = Executors.newCachedThreadPool()
        println("main thread 1")
        var task = Callable<Int> {
            println("child thread calc")
            Thread.sleep(3000)
            var sum = 0
            for(i in 0..99){
                sum += i
            }
            return@Callable sum
        }

        var result = executor.submit(task)
        executor.shutdown()

        try {
            Thread.sleep(1000)
        } catch (e: Exception) {
        }

        try {
            var r = result.get()
            println("main thread result:$r")
        } catch (e: Exception) {

        }
        println("main thread finished")
    }

result.get() 会等待子线程返回结果。

FutureTask 例子

/*FutureTask 可以查询状态,已经取消,callable就是和runnable一样,只能执行,无法操作和获取状态*/
    fun runAction4(){
        var executor = Executors.newCachedThreadPool()
        println("main thread 1")
        var task = Callable<Int> {
            println("child thread calc")
            Thread.sleep(3000)
            var sum = 0
            for(i in 0..99){
                sum += i
            }
            return@Callable sum
        }
        var futureTask = FutureTask<Int>(task)

        executor.submit(futureTask)
        executor.shutdown()
        try {
            Thread.sleep(1000)
        } catch (e: Exception) {
        }

        try {
            var r = futureTask.get()
            println("main thread result:$r")
        } catch (e: Exception) {

        }
        println("main thread finished")
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注