有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

请建议最好的方法是什么

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

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    若要处理多个线程,应同步列表。请参阅下面的代码,以在同步块和线程安全中的子列表之间拆分列表

        List xList= Collections.synchronizedList(new ArrayList(10));
    
         synchronized(xList){
         List aList=xList.subList(0, 5);
         List bList=xList.subList(5, 10);
         }
    
  2. # 2 楼答案

    为了能够作为程序的异步元素处理某些内容,您必须为该操作启动新线程。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

  3. # 3 楼答案

    你的问题太模糊了。一般的答案是为每个列表生成一个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();
        }
    }