2009-09-04 37 views
2

我有以下代码。如果我在演员身体内对“foo()”的调用发表评论,代码就可以正常工作。但是,如果“foo()”被激活...我的代码冻结!演员死于Scala内部的方法调用

任何kwnows为什么?

import scala.actors.Actor._ 

object Main extends Application{ 
    def foo() = { 
     println("I'm on foo") 
    } 

    def testActor() = { 
     val target = self 

     for(i <- 1 to 100){ 
      actor{ 
       foo() 
       target ! i 
      } 
     } 

     var total = 0 
     receive{ 
      case x:Int => total += x 
     } 
     total 
    } 

    println("Result: " + testActor()) 
} 

回答

2

当“Main”类正在初始化时调用“testActor”。参与者代码在另一个线程(不是主线程)中执行,并且被阻塞,并且不能发送任何消息,因为它试图访问正在主线程中初始化的类中的一个方法(Main,在这种情况下)。 “接收”挂起,因为它不能收到任何消息。

请勿使用“扩展应用程序”。使用“def main(args:Array [String])”并为自己节省很多麻烦。

http://scala-blogs.org/2008/07/application-trait-considered-harmful.html

2

Application性状及其用法在这里有问题。当代码在Application的方法中运行而不是在main方法中运行时,该代码实际上是作为构造函数的一部分运行的。所以在你调用testActor()方法的时候,这个对象还没有真正完成初始化。

为了解决这个问题,移动的println线为主要方法:

def main (args: Array[String]) { 
    println("Result: " + testActor()) 
} 

因为这个问题这么轻易发生,Application特点被认为是坏消息。

+0

如此地:http://stackoverflow.com/questions/1332574/common-programming-mistakes-for-scala-developers-to-avoid/1334962#1334962 – 2009-09-04 16:13:50