【问题标题】:How to use a method in Multi-Threads Class which implements Runnable如何在实现 Runnable 的多线程类中使用方法
【发布时间】:2015-03-08 21:24:40
【问题描述】:

我正在制作一个多线程应用程序。实现 Runnable 的类有一个返回 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;
   }
}

需要使用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) {
}

【问题讨论】:

    标签: java multithreading arraylist runnable


    【解决方案1】:

    您可以将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
    }
    

    【讨论】:

      【解决方案2】:

      您可以简单地维护第二个数组,其中每个线程都有 SearchThread 可运行。

      【讨论】:

        猜你喜欢
        • 2012-11-02
        • 2015-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多