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;
}
}
如上面评论中所示,我需要暂停线程几秒钟。希望你能帮助我。
谢谢你的时间!
答案 0 :(得分:0)
只需拨打Thread.sleep(timeInMillis)
- 这将暂停当前主题。
所以:
Thread.sleep(5000); // Sleep for 5 seconds
显然,您不应该从UI线程执行此操作,否则您的整个UI将冻结......
请注意,这种简单的方法不允许通过中断线程唤醒其他线程。如果您希望能够尽早将其唤醒,可以在显示器上使用Object.wait()
,无论哪个代码都需要将其唤醒;该代码可以使用Object.notify()
来唤醒等待的线程。 (或者,使用更高级别的抽象,例如Condition
或Semaphore
。)
答案 1 :(得分: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;
}