[英]How to use a method in Multi-Threads Class which implements Runnable
我正在制作一个多线程应用程序。 实现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) {
}
您可以将对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
}
您可以简单地维护第二个数组,该数组具有每个线程可运行的SearchThread
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.