我有一个例如for (int i=1;i<=10;i++)
的循环,我想在其中创建10个线程,每个线程对一组数据执行相同的任务并返回结果。然后在循环内处理此结果。任何想法如何做到这一点?
for (int i=1;i<=10;i++) {
Work w = new Work();
Thread t = new Thread(w);
w.getResultFromThread();
//process w
}
class Work implements Runnable {
public void run() {
//perform tasks
}
public int getResultFromThread() {
return result;
}
}
我希望每个线程并行工作,但是当我逐个接收结果时。
答案 0 :(得分:2)
如果您不想使用执行程序,可以通过以下方式执行:
int size = 10;
Thread[] threads = new Thread[size];
Work[] works = new Work[size];
for (int i = 1; i <= size; i++) {
Work w = new Work();
works[i - 1] = w;
Thread t = new Thread(w);
threads[i - 1] = t;
// Start the thread
t.start();
}
// now you have started all the threads
for (int i = 0; i < size; i++) {
// wait for each thread to complete execution, before extracting the result
// [here i am assuming that getResultFromThread() does not block
// till we get the result, if it blocks, then no need to join]
threads[i].join();
int result = works[i].getResultFromThread();
// do something with the result
}
答案 1 :(得分:1)
ArrayList<Work> listOfJobs = new ArrayList<Work>();
ArrayList<Thread> threadList = new ArrayList<Thread>();
for(int i = 0 ; i < 10; i++) {
Work w = new Work();
listOfJobs.add(w);
Thread t = new Thread(w);
threadList.add(t);
t.start();
}
for(Thread t : listOfJobs) {
t.join();
w.getResultsFromThread();
}
这样,无论出于何种原因,您都不需要执行程序。
首先,您创建所有线程并启动它们(第一个循环),然后在它们上调用join
,以确保您想要获得结果的线程完成(第二个循环)。
您始终可以将listOfJobs
传递给其他方法来处理结果。