2012-02-15 46 views
1

我試圖與pool.shutdown()和pool.awaitTermination(0,TimeUnit.SECONDS),但它並不真正希望等待的任務做它打印在我之前加入方法它已完成。我究竟做錯了什麼。順便說一句:游泳池本身是我迄今爲止多任務處理所看到的最好的東西。很高興我在這裏找到了!帶有像CountDownLatch這樣的信號的解決方案似乎並不是最常用的方法......我正在尋找更多像join方法那樣的東西,因爲它是針對線程實現的。Groovy的併發執行,等待終止像線程

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!' 

回答

4

嘗試使用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() 
+0

非常感謝,這正是該解決方案,並與偉大工程我擴展Thread。謝謝!!! – Booyeoo 2012-02-17 09:21:58

+0

讓你的對象成爲線程服務沒有任何用處,我希望他們只是實現Runnable。這並不是什麼大不了的事情,因爲你沒有啓動線程,但它確實有開銷。 – 2012-02-17 15:41:57

1

您正等待0秒完成任務。你應該等待一段有意義的時間,也許10秒?或1分鐘?

pool.awaitTermination(1, TimeUnit.MINUTES); 

只是一個FYI的awaitTerminiation將等待指定的時間,除非所有當前排隊的項目完成。如果他們完成該方法將退出,你會得到你的println聲明

編輯:

只注意到你提交線程執行人的服務。你只應該提交Runnables。由於Thread正在編譯,因爲Thread實現了Runnable實際發生的是執行程序服務的Thread將Runnable(在這裏是您的線程)從工作隊列中取出並執行其run()方法。因此不需要提交線程。

4

我相信要等待「永遠」,你需要通過魔法參數:

pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)