微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【原创】大叔经验分享73scala akka actor

import java.util.concurrent.{ExecutorService, Executors, TimeUnit}
import akka.actor.{Actor, ActorSystem, Props}
import akka.util.Timeout
import scala.concurrent.{Await, ExecutionContext}
import scala.concurrent.duration.Duration

 

Runnable

无返回值

  class TestActor extends Actor {
    def receive = {
      case arg => {
        println("got : " + arg)
        Thread.sleep(1000)
      }
    }
  }

同步调用

val system = ActorSystem("ActorSystem")
val actor = system.actorOf(Props(new TestActor), "TestActor")
actor ! "whatever"

Callable

有返回值

  class TestActor extends Actor {
    def receive = {
      case arg => {
        println("got : " + arg)
        Thread.sleep(1000)
        sender ! "hello : " + arg
      }
    }
  }

异步调用

    val system = ActorSystem("ActorSystem")
val actor = system.actorOf(Props(new TestActor), "TestActor")
    implicit val timeout = Timeout(10000, TimeUnit.SECONDS)
    import akka.pattern._

//1 val feature = actor ? "whatever" while (!feature.isCompleted) Thread.sleep(1000) println(feature.isCompleted) if (feature.isCompleted) {println(feature.value.get.isSuccess + ", " + feature.value.get.get);}
//2 println(Await.result(feature, Duration.create(1, TimeUnit.SECONDS)))

更多

并发控制

  val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(100))
  val system = ActorSystem("ActorSystem", None, None, Option(ec))

定时

    val system = ActorSystem("ActorSystem")
    system.scheduler.schedule(Duration.create(1, TimeUnit.SECONDS), Duration.create(1, TimeUnit.SECONDS))({
      println("trigger : " + System.currentTimeMillis)
    })(ec)

 

注意Actor相当于java中的单实例单线程,可以通过多个Actor来控制并发

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐