您可以运行这个例子作为一个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的回答我得到了一些运作良好的东西,我将它添加为答案 –