Runnable示例
import java.util.concurrent.{
Executors,
ExecutorService}
object Test {
def main(args:
Array[
String]) {
val threadPool:
ExecutorService=
Executors.newFixedThreadPool(
5)
try {
for(i <-
1 to
5){
threadPool.execute(
new ThreadDemo(
"thread"+i))
}
}
finally {
threadPool.shutdown()
}
}
class ThreadDemo(threadName:String) extends Runnable{
override def run(){
for(i <-
1 to
10){
println(threadName+
"|"+i)
Thread.sleep(
100)
}
}
}
}
Callable示例
import java.util.concurrent.{
Callable,
FutureTask,
Executors,
ExecutorService}
object Test {
def main(args:
Array[
String]) {
val threadPool:
ExecutorService=
Executors.newFixedThreadPool(
3)
try {
val future=
new FutureTask[
String](
new Callable[
String] {
override def call():
String = {
Thread.sleep(
100)
return "im result"
}
})
threadPool.execute(future)
println(future.get())
}
finally {
threadPool.shutdown()
}
}
}