转载

Scala学习笔记<2>:异步FutureTask实例

Scala学习笔记<2>:异步FutureTask实例

Scala学习笔记&lt;2&gt;:异步FutureTask实例

实例代码:

package com.blogchong.scala.futuretask  import java.util.concurrent.{FutureTask, Callable, TimeUnit}  /**  * Author:  blogchong  * Blog:    www.blogchong.com  * Mailbox: blogchong@163.com  * Data:    2015/8/25  * Describe: 异步futuretask实例  */  calss FutureTaskExample {   //异步请求方法   def getAsyn(testList: util.List[Any]) = {      //添加异步请求。注意FutureTask定义的返回值,可以随意定义,但是与call返回值对应     val tasks: util.List[FutureTask[String]] = new util.ArrayList[FutureTask[String]]()     testList.map {       f =>         val futureTask: FutureTask[String] = new FutureTask(new Callable[String] {           def call: String = {             //具体需要做的异步操作,比如请求http             "any" //返回值,定义的是String           }         });         tasks.add(futureTask)         threadPoolService.executor(Names.CACHED).execute(futureTask)     }      //串行获取异步请求结果     val lres = new util.ArrayList[String]()     tasks.map {       f =>         val task: FutureTask[String] = f         try {           val sinfo = task.get(30000, TimeUnit.MILLISECONDS)           lres.add(sinfo)         } catch {           case e: Exception => {             logger.error("异步请求出错:" + e.printStackTrace)             task.cancel(true)           }         }     }      //获取请求的值     lres.map {       dd =>         JSONArray.fromObject(dd).map {           kks =>           //具体解析过程         }     }   } }
正文到此结束
Loading...