我在pool.shutdown()和pool.awaitTermination(0,TimeUnit.SECONDS)中尝试过,但它真的不想等到任务完成后再打印它已经完成。我做错了什么。BTW:游泳池本身是我今天看到的最适合多任务处理的东西。很高兴我在这里找到它!!!像CountDownLatch这样的信号解决方案似乎不是最棒的方式。。。我正在搜索更多类似join方法的东西,因为它是为Threads实现的。
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import groovy.transform.Synchronized
import java.util.concurrent.*
class myThread extends Thread{
Integer timer=0
Integer count=0
String tn=''
String status=''
def counter = new AtomicInteger()
def void run() {
println tn+' started ---- !!! ----'
status='running'
for( i in 1..count ) {
sleep timer
println tn+" Doing something loop $i"
counter.incrementAndGet()
}
println tn+' finished - ### -'
status='ok'
this.join()
}
}
def queue=[]
def mt1=new myThread(timer:550,count:10,tn:'t1',status:'')
def mt2=new myThread(timer:530,count:6,tn:'t2',status:'')
def mt3=new myThread(timer:550,count:10,tn:'t3',status:'')
def mt4=new myThread(timer:500,count:6,tn:'t4',status:'')
queue.push(mt1)
queue.push(mt2)
queue.push(mt3)
queue.push(mt4)
def maxConcurrent=2
def pool = Executors.newFixedThreadPool(maxConcurrent)
queue.each(){
pool.submit(it)
}
pool.shutdown()
pool.awaitTermination(0, TimeUnit.SECONDS);
// HOW DO I WAIT HERE???
println 'NOW its REALLY!!! finished!'
尝试使用ExecutorCompletionService
def pool = Executors.newFixedThreadPool(maxConcurrent)
def ecs = new ExecutorCompletionService<Void>(pool);
queue.each {
ecs.submit(it, Void); // I think this is how to handle a void return
}
// take blocks until task finished so get probably not needed in this case
queue.each {
ecs.take().get();
}
pool.shutdown()
我相信要"永远"等待,你需要传递神奇的参数:
pool.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS )
您等待任务完成的时间为0秒。你应该等待一段有意义的时间,也许是10秒?还是1分钟?
pool.awaitTermination(1, TimeUnit.MINUTES);
仅供参考,awaitTerminiation将等待指定的时间,除非所有当前排队的项目都完成。如果他们完成,方法将退出,您将进入println
语句
编辑:
刚刚注意到您正在向执行器服务提交线程。您应该只提交Runnables。假设它是编译的,因为Thread实现了Runnable。实际发生的是执行器服务的Thread将Runnable(这里是线程)从工作队列中取出,并执行其run()方法。因此不需要提交线程。