Created
April 8, 2011 20:31
-
-
Save tc/910661 to your computer and use it in GitHub Desktop.
Different java concurrency usage in scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fetch(val url:String) extends Runnable{ | |
override def run{ | |
println(scala.io.Source.fromURL(url).mkString) | |
} | |
} | |
val urls = List("http://news.com", "http://cnn.com", "http://stackoverflow.com", "http://abc.com") | |
val threads = urls.map{ url => | |
val thread = new Thread(new Fetch(url)) | |
thread.start() | |
thread | |
} | |
while(threads.exists(thread => thread.isAlive)){ } | |
println("done!") | |
////// | |
import java.util.concurrent.Callable | |
import java.util.concurrent.ExecutorService | |
import java.util.concurrent.Executors | |
import java.util.concurrent.Future | |
class Fetch(url:String) extends Callable[String] { | |
override def call:String = { | |
scala.io.Source.fromURL(url).mkString | |
} | |
} | |
val executor = Executors.newFixedThreadPool(5) | |
val urls = List("http://news.com", "http://cnn.com", "http://stackoverflow.com", "http://abc.com") | |
val list = urls.map{ | |
url => | |
val worker = new Fetch(url) | |
executor.submit(worker) | |
} | |
val allContents = list.map{ | |
future => future.get | |
}.mkString | |
println(allContents) | |
println(allContents.length) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment