scala并发编程第4章习题

1

package com.linewell.chapter4

import java.util.{TimerTask, Timer}

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future, Promise}
import scala.io.Source
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

/** * Created by ctao on 15-12-13. */
object UrlTest extends App {
  val timer = new Timer(true)

  def timeout(t: Long, p: Promise[String]) = {
    timer.schedule(new TimerTask {
      override def run(): Unit = {
        p.trySuccess(s"timeout $t")
      }
    }, t)
  }

  def stopTimer(timer: Timer) = {
    timer.cancel()
    timer.purge()
  }

  def waitPrint(t: Timer): Unit = {
    t.schedule(
      new TimerTask {
        override def run(): Unit = print(".")
      },0,50
    )
  }

  while (true) {
    println("Please input url")
    val input = io.StdIn.readLine()
    val p = Promise[String]
    val dotPrinterTimer = new Timer(true)

   Future {
      timeout(2000, p)
      Source.fromURL(input).mkString
    } onComplete {
      case Success(s) => p.trySuccess(s)
      case Failure(e) => p.trySuccess(s"error :${e.toString}")
    }

    Future {
      println("Wait")
      waitPrint(dotPrinterTimer)
    }

    val res = Await.result(p.future, Duration.Inf)

    stopTimer(dotPrinterTimer)
    println(res)

  }
}

2

package com.linewell.chapter4

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Promise}
import scala.util.Try


/** * Created by ctao on 15-12-10. */
object IVarTest extends App{
  class IVar[T]{
    val value  = Promise[T]
    def apply():T =  if(!value.isCompleted) throw new Exception("no value") else Await.result(value.future,Duration.Inf)
    def :=(x:T) :Unit = if(! value.tryComplete(Try(x))) throw new Exception("have value")
  }

  val iVar = new IVar[String]

  import com.linewell.chapter2.thread
  (1 to 10).foreach{i =>
    thread{
      try{
        iVar := s"${Thread.currentThread().getName}"
      }catch {
        case e:Throwable => println(s"error :${e.getMessage}, value = ${iVar.apply()}")
      }
    }

  }
}

3

package com.linewell.chapter4

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global

/** * Created by ctao on 15-12-10. */
object ExistsFutureTest extends App{

  implicit  class MyFuture[T](self:Future[T]){
    def exists(p:T => Boolean) = self.map(p)
  }

  val hello = Future("hello")
  val world = Future("world")
  def startWithH(str:String) = str.startsWith("h")

  println(Await.result(hello.exists(startWithH),Duration.Inf))
  println(Await.result(world.exists(startWithH),Duration.Inf))
}

4

package com.linewell.chapter4

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future, Promise}
/** * Created by ctao on 15-12-10. */
object FutureAndPromiseTest extends App{

  implicit class MyFuture[T](self:Future[T]){

    def exists(p : T => Boolean) = {
      val value =Promise[Boolean]
      self.foreach((t:T) => value.success(p(t)))
      self.failed.foreach(_ => value.success(false))
      value.future
    }
  }


  val hello = Future("hello")
  val world = Future("world")
  def startWithH(str:String) = str.startsWith("h")

  println(Await.result(hello.exists(startWithH),Duration.Inf))
  println(Await.result(world.exists(startWithH),Duration.Inf))

}

5

package com.linewell.chapter4
import scala.async.Async.{async,await}
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global

/** * Created by ctao on 15-12-10. */
object AsyncTest extends App{
 implicit class MyFuture[T](self:Future[T]){
    def exists(p:T => Boolean):Future[Boolean] = async
    {
      val value = await{
        self
      }
      p(value)
    }.recover{case _ => false}
  }


  val hello = Future("hello")
  val world = Future("world")
  def startWithH(str:String) = str.startsWith("h")

  println(Await.result(hello.exists(startWithH),Duration.Inf))
  println(Await.result(world.exists(startWithH),Duration.Inf))

}

6

package com.linewell.chapter4

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.sys.process._
import scala.concurrent.ExecutionContext.Implicits.global

/** * Created by ctao on 15-12-10. */
object SpawnTest extends App{
  def spawn(command:String) :Future[Int] = Future{
    command.!
  }

  println(Await.result(spawn("ls /"),Duration.Inf))
}

7

package com.linewell.chapter4

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Promise, Future}
import java.util.concurrent.ConcurrentHashMap
import scala.util.Try

/** * Created by ctao on 15-12-10. */
object IMapTest extends App {

  class IMap[K, V] {
    import scala.collection.convert.decorateAsScala._
    private val map = new ConcurrentHashMap[K, Promise[V]]().asScala

    private def createPromise(v: V) = {
      val p = Promise[V]
      p.success(v)
      p
    }

    def update(k: K, v: V): Unit = {
     map.putIfAbsent(k,createPromise(v)) match {
       case Some(p) =>
         try{
           p.success(v)
         }catch {
           case e:IllegalStateException => throw  new Exception("key in")
           case e:Throwable => throw e
         }
       case None =>

     }
    }

    def apply(k: K): Future[V] = map.get(k) match {
      case Some(p) => p.future
      case None => Promise[V].future
    }


  }

  import com.linewell.chapter2.thread

  val m = new IMap[Int, String]()
  (1 to 100).map(i => thread {
    m.update(1, Thread.currentThread().getName)
  })

  (1 to 100).map(i => thread {
   println(Await.result(m.apply(1),Duration.Inf))
  })
}

8

package com.linewell.chapter4

import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

/** * Created by ctao on 15-12-11. */
object PromiseTest extends App{
  implicit  class MyPromise[T](self:Promise[T]){
    def compose[S](f: S =>T) ={
      val ps = Promise[S]
      ps.future.onComplete{
        case Success(s) => Future(self.trySuccess(f(s)))
        case Failure(e) => self.tryFailure(e)
      }
    }
  }
}

你可能感兴趣的:(scala,并发)