如何通过不同的进程同时处理两个线程?

时间:2013-07-03 08:55:30

标签: java spring java-ee

我通过调用一些方法从DB获得了一个List X.现在我将列表拆分为两个单独的列表A& B按一些标准。

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

请告知最佳方法。

我的是春季网络应用程序。这仅适用于特定服务。

先谢谢

3 个答案:

答案 0 :(得分:1)

你的问题太模糊了。一般答案是为每个列表生成Thread并处理它们。

(未经测试但应该可以正常工作)

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

答案 1 :(得分:0)

要使用多个线程,您的列表应该同步。请参阅下面的代码,以便在synchronized块中的子列表和线程安全之间拆分List。

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

     synchronized(xList){
     List aList=xList.subList(0, 5);
     List bList=xList.subList(5, 10);
     }

答案 2 :(得分:0)

为了能够将某些东西作为程序的异步元素处理,您必须为该操作启动新的Thread。在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();

}

You should read the tutorial