我正在制作一个多线程应用程序。实现Runnable的类有一个返回ArrayList的方法。我如何在我的主要使用该方法?
class SearchThread implements Runnable {
private ArrayList<String> found;
//Constructor
public SearchThread (String[] dataArray) {/**/}
public void run() {
try{
//Do something with found
}
Thread.sleep(time);
System.out.println("Hello from a thread!");
}
catch (Exception e){}
}
public ArrayList<String> getResult() {
return found;
}
}
需要使用getResult方法的主类。
ArrayList<String> result;
Thread[] threads = new Thread[data.length];
for (int i = 0; i < data.length; i++) {
threads[i] = new Thread(new SearchThread(data[i]));
threads[i].start();
}
try {
for (int i = 0; i < data.length; i++) {
threads[i].join();
result = // need to use the getResult()
}
} catch (Exception e) {
}
答案 0 :(得分:0)
您可以将对SearchThread
的引用存储在另一个数组中,并在相应的线程加入后访问它们。我举个例子:
ArrayList<String> result;
Thread[] threads = new Thread[data.length];
SearchThread[] searchThreads = new SearchThread[data.length];
for (int i = 0; i < data.length; i++) {
searchThreads[i] = new SearchThread(data[i]);
threads[i] = new Thread(searchThreads[i]);
threads[i].start();
}
try {
for (int i = 0; i < data.length; i++) {
threads[i].join();
result.add(i, searchThreads[i].getResult() ? "found"
: "not found");
}
} catch (InterruptedException e) {
// do something meaningful with your exception
}
答案 1 :(得分:0)
您可以简单地维护第二个数组,其中每个线程都有SearchThread
可运行。