0

我通过调用一些方法从 DB 中获得了 List X。现在我按照某些标准将列表分成两个单独的列表 A 和 B。

这两个列表必须以不同的方式处理。但我希望同时开始处理这两个列表。不想等待并开始处理第二个。

请建议最好的方法是什么。

我的是 Spring Web 应用程序。这仅适用于特定服务。

提前致谢

4

3 回答 3

1

Your question is too vague. A generic answer would be to spawn a Thread for each list and process them.

(Not tested but should work fine)

class ListAProcessor implements Runnable {

    private final List<YourListClass> list;

    public ListAProcessor(final List<YourListClass> yourListA) {
        this.list = yourList;
    }

    @Override
    public void run() {
        // Process this.list
    }

}

class ListBProcessor implements Runnable {

    private final List<YourListClass> list;

    public ListBProcessor(final List<YourListClass> yourListB) {
        this.list = yourList;
    }

    @Override
    public void run() {
        // Process this.list
    }
}

public class Main {
    public static void main(final String args[]) {
        List<YourListClass> listA;
        List<YourListClass> listB;
        // Initialize the lists
        Runnable processor = new ListAProcessor(listA);
        processor.start();
        processor = new ListBProcessor(listB);
        processor.start();
    }
}
于 2013-07-03T08:57:05.960 回答
0

为了能够将某些东西作为程序的异步元素进行处理,您必须为该操作启动新线程。在 Java 中存在特殊的 API,支持这种类型的操作。

您将需要使用类Thread和接口Runnable

{ //Body of some method

     List<Object> sourceList = getList();

     final List<Object> firstList  = createFirstList(sourceList);
     final List<Object> secondList = createsecondList(sourceList);

     //Define the Runnable, that will store the logic to process the lists.

     Runnable processFirstList = new Runnable() {//We create anonymous class
         @Override
        public void run() {
              //Here you implement the logic to process firstList
       }

     };


     Runnable processSecondList = new Runnable() {//We create anonymous class
        @Override
        public void run() {
              //Here you implement the logic to process secondList
       }

     };

     //Declare the Threads that will be responsible for execution of runable logic

     Thread firstListThread  = new Thread(processFirstList);
     Thread secondListThread = new Thread(processSecondList);

     //Start the Threads 

     firstListThread.start();
     secondListThread.start();

}

你应该阅读教程

于 2013-07-03T09:15:28.010 回答
0

要工作不止一个线程,您的列表应该是同步的。请参阅下面的代码以在同步块中的子列表之间拆分列表以及线程安全。

    List xList= Collections.synchronizedList(new ArrayList(10));

     synchronized(xList){
     List aList=xList.subList(0, 5);
     List bList=xList.subList(5, 10);
     }
于 2013-07-03T09:03:14.337 回答