Java中 Future类中 get 的使用

* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
onst val TAG = "TestFuture"

class MainActivity : AppCompatActivity() {
    private var mExeService: ExecutorService = Executors.newSingleThreadExecutor()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var futureResult = mExeService.submit(
                Callable<String> {
                    Log.d(TAG, "call begin")
                    try {
                        Thread.sleep(10 * 1000)
                    } catch (e: InterruptedException) {
                        Log.d(TAG, "InterruptedException: " + Log.getStackTraceString(e))
                    }
                    Log.d(TAG, "call end")
                    "call success"
                })
        try {
            Log.d(TAG, "futureResult : " + futureResult.get(5 * 1000, TimeUnit.MILLISECONDS))
        } catch (e: TimeoutException) {
            Log.d(TAG, "TimeoutException: " + Log.getStackTraceString(e))
            futureResult.cancel(true)//取消在线程中的任务,如果cancel,即使get抛出exception,原来的任务仍然继续执行
        }
    }

}

猜你喜欢

转载自my.oschina.net/sfshine/blog/1818252
今日推荐