2012-07-09 158 views
0
ExecutorService exec = Executors.newFixedThreadPool(8); 
List<Future<Object>> results = new ArrayList<Future<Object>>(); 

// submit tasks 
for(int i = 0; i < 8; i++) { 
    results.add(exec.submit(new ThreadTask())); 
} 

... 

// stop the pool from accepting new tasks 
exec.shutdown(); 

// wait for results 
for(Future<Object> result: results) { 
    Object obj = result.get(); 
} 


class ThreadTask implements Callable<Object> { 

    public Object call() { 
     // execute download 
     //Inside this method I need to pause the thread for several seconds 
     ... 
     return result; 
    } 
} 

如上面的評論中所示,我需要暫停線程幾秒鐘。希望你能幫助我。Android:暫停線程幾秒

謝謝你的時間!

回答

0

只需撥打Thread.sleep(timeInMillis) - 將暫停當前線程。

所以:

Thread.sleep(5000); // Sleep for 5 seconds 

顯然,你不應該從一個UI線程,或者你的整個UI將凍結做到這一點...

注意,這個簡單的方法不會允許線程通過打斷它而被喚醒。如果您希望能夠提前將其喚醒,您可以在監視器上使用Object.wait(),該監視器可供需要喚醒的代碼訪問;該代碼可以使用Object.notify()來喚醒等待線程。 (或者,使用更高級別的抽象,如ConditionSemaphore。)

0

你可以實現一個新的線程,這是不是UI線程..

這樣的事情可能會爲你做吧..

class ThreadTask implements Callable<Object> { 

public Object call() { 
Thread createdToWait= new Thread() { 
     public void run() { 
        //---some code 

        sleep(1000);//call this function to pause the execution of this thread 

        //---code to be executed after the pause 
     } 
    }; 
    createdToWait.start(); 
return result; 
}