while(startYear <= endYear){
try {
GetNamesThread st = new GetNamesThread(startYear, numNames, allNames);
st.start();try {
st.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startYear++;
}
所以基本上我经历一个循环并且每次运行一个不同的线程并在开始下一个线程之前完成该线程。我无法弄清楚如何运行从startYear到endYear的所有线程。任何想法或建议从哪里开始?
答案 0 :(得分:2)
将创建的线程保留在列表中,并在第一个循环中启动它们中的每一个而不执行join()。然后迭代列表并加入每个线程。
List<GetNamesThread> threads = new ArrayList<GetNamesThread>();
while(startYear <= endYear){
try {
GetNamesThread st = new GetNamesThread(startYear, numNames, allNames);
st.start();
threads.add(st);
} catch (IllegalThreadStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startYear++;
}
for (GetNamesThread thread : threads) {
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}