この例を Groovy スクリプトとして実行できます。
@Grapes(
@Grab(group='org.codehaus.gpars', module='gpars', version='1.2.1')
)
import java.util.concurrent.*
import groovyx.gpars.*
def doSomethingThatTakesSomeTime(){
println "calculating..."
for(long i: 0..100){
Thread.sleep(i)
}
println "*done*"
"Done with doSomethingThatTakesSomeTime"
}
def doSomethingElse(){
for(int x:0..1000) print "."
println "doSomethingElse done."
}
/**
* runs a job and return job id for later montoring.
*/
def runJob(){
GParsPool.withPool(){
Future future = createJob() // returns immediately
doSomethingElse() //Do someting else while the async process is running
//Ok, thats done, but the longer runningprocess is still running, return the future
future
}
}
Future createJob(){
//create a new closure, which starts the original closure on a thread pool
Closure asyncFunction = { doSomethingThatTakesSomeTime() }.async()
//Invoke the function, return a Future
asyncFunction()
}
def job = runJob()
//println "\n\nResult is: " + job.get()
スクリプトを「そのまま」実行すると、スクリプトが実行され、実行時間の長いジョブが出力*done*
され、実際に最後まで実行されたことが示されます。ただし、呼び出しを行う下部の行Future.get()
はコメント アウトされており、呼び出されていません。
最後の行のコメントを外すと、呼び出しの結果として完了すると、結果が出力されます。Future.get()