如何在实现 Runnable 的多线程 Class 中使用方法

How to use a method in Multi-Threads Class which implements Runnable

我正在制作一个多线程应用程序。实现 Runnable 的 class 有一个 returns ArrayList 的方法。我如何在我的 main 中使用该方法?

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;
   }
}

Mainclass需要使用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 可运行。