您可以運行這個例子作爲一個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()
「在上面的情況中,任務獲勝沒有運行,因爲沒有呼叫.get()「:這是不正確的。任務(..)'創建一個任務(Runnable)並且用這個任務調用'pool.execute'(這顯然是執行的 - 線程模型取決於你使用的池的實現)。 –
感謝您的評論,基於它和@ pczeus的回答我得到了一些運作良好的東西,我將它添加爲答案 –