2012-07-09 155 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; 
}