我是一个新的 java 编码器,最近被告知要检查 scala 的并发实现。我想一个简单的(尽管不是最好的说明并发性)示例可能是让演员解决 Eratosthenes 的筛子。到目前为止,我已经拼凑出一些东西,但我不确定我要去的方向是否接近正确。这是我当前的代码:
import scala.actors.Actor
import scala.actors.Actor._
import Array._
class PrimeActor(val id: Int) extends Actor {
//Runs one Prime of the Sieve of Eratosthenes
def sieve(p: Int, list: Array[Int]) {
var i = 1
var place = 0
while(list contains (i * p)) {
place = list.indexOf(i * p)
if (list(place) != 0)
list.update(place, 0)
i += 1
}
}
//Checks to see if there is a higher prime in the list
//If so, creates a new actor to handle it and sends
//it the list and the prime
def findandCreateNextPrime(p: Int, list: Array[Int]){
var i = 1
var place = list.indexOf(p)
while(list(place + i) == 0 && (p + i) <= list.last) {
i += 1
}
val newP = list(place+i)
if (list contains (p + i)) {
if ((p + i) equals list.last) {
print(list.last)
} else {
print(", ")
val pA = new PrimeActor(newP)
pA.start()
pA ! (list(newP), list)
}
} else {
println("DONE")
}
}
//Actor behavior
def act() {
loop {
react{
case (recievedP: Int, recievedList: Array[Int]) =>
print(recievedP)
sieve(recievedP, recievedList)
findandCreateNextPrime(recievedP, recievedList)
exit()
}
}
}
}
任何帮助或方向输入将不胜感激。谢谢!