简体   繁体   中英

Multithreading- creating new thread for each loop

I don't know that much about multi threading but I think that it may be of use to what I am doing. I have something that loops through each graphicNode in my xml file, and creates an object based on the information read. Depending on the object it can take in a query / queries or it will use a stored procedure. The object is then stored in an arrayList. This ends up with my program taking about a minute to start. Is there a way I can create a new thread each time it goes through the loop? Here is my code:

            File fXmlFile = f;
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            //Normalize the xml file(document)
            doc.getDocumentElement().normalize();

            // All of the nodelists that the XML file uses
            NodeList graphicNodeList = doc.getElementsByTagName("graphic");
            NodeList locationNodeList = doc.getElementsByTagName("location");
            NodeList gUINodeList  = doc.getElementsByTagName("GUI");
            NodeList storedProcedureNodeList  = doc.getElementsByTagName("storedProcedure");
            NodeList parameterNodeList = doc.getElementsByTagName("parameter");
            NodeList dialSpecificNodeList = doc.getElementsByTagName("dialSpecific");
            NodeList queriesNodeList=doc.getElementsByTagName("queries");
            NodeList tickerSpecificNodeList=doc.getElementsByTagName("tickerSpecific");
            doc.getElementsByTagName("category");


            // Main loop to get information from each graphical Element.
            for (int temp = 0; temp < graphicNodeList.getLength(); temp++) {
                // Sets the node to the first item in the nodeList
                Node graphicNode = graphicNodeList.item(temp);


                String chartType;

                if (graphicNode.getNodeType() == Node.ELEMENT_NODE) {
                    // Makes an element based off the node.
                    Element eElement = (Element) graphicNode;

                    //Get the Chart type so the system knows what to do with it.
                    chartType= eElement.getAttribute("type");

                    if(chartType.equals("barChartVsTime")){
                        createBarChartVsTime(graphicNode, gUINodeList,locationNodeList, storedProcedureNodeList, parameterNodeList, eElement);
                    }
                    if(chartType.equals("sqlTable")){
                        createSQLTable(graphicNode, gUINodeList, eElement);
                    }
                    if(chartType.equals("dialChart")){
                        createDialChart(graphicNode, gUINodeList, dialSpecificNodeList, eElement);
                    }
                    if(chartType.equals("hourlyDialChart")){
                        createHourlyDialChart(graphicNode, gUINodeList, dialSpecificNodeList, eElement);
                    }
                    if(chartType.equals("colorBlock")){
                        createColorBlock(graphicNode, gUINodeList, eElement);
                    }
                    if(chartType.equals("image")){
                        createImageBlock(graphicNode, gUINodeList, eElement);
                    }
                    if(chartType.equals("threePointAverageChart")){
                        createThreePointAverageChart(graphicNode, gUINodeList,locationNodeList, storedProcedureNodeList, parameterNodeList, eElement);
                    }
                    if(chartType.equals("yieldDialChart")){
                        createYieldDialChart(graphicNode, gUINodeList, locationNodeList, storedProcedureNodeList, dialSpecificNodeList, parameterNodeList, eElement);
                    }

                    if(chartType.equals("ticker")){
                        createTicker(graphicNode, gUINodeList,tickerSpecificNodeList, queriesNodeList, eElement);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I don't know that much about multi threading but I think that it may be of use to what I am doing.

This ends up with my program taking about a minute to start

You're getting ahead of yourself. You should profile your code, first, to see where you're taking the performance hit. Take a look at VisualVM for this. You might have accidentally written an O(n^2) algorithm.

Depending on the object it can take in a querie(s) or it will use a stored procedure.

I bet it's here. You might be better served by connection pooling or batch requests than immediately diving into threading.

This question address a similar problem.

So basically you need to create a new runnable for each task, Below is an example (Although I have not tested it but will give you an idea):

Dispatcher.java

package com.test.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Dispatcher {

    public void dispatch() throws InterruptedException, ExecutionException {
        ExecutorService cachePool = Executors.newCachedThreadPool();
        for (TaskName taskName : TaskName.values()) {
            cachePool.submit(taskName.worker());
        }
        cachePool.awaitTermination(5, TimeUnit.MINUTES);
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        new Dispatcher().dispatch();
    }
}

TaskName.java

package com.test.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public enum TaskName {
    BarChartVsTime {
        @Override
        public Runnable worker(Document doc) {
            return new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread1");
                    //createBarChartVsTime(graphicNode, gUINodeList,locationNodeList, storedProcedureNodeList, parameterNodeList, eElement);
                }
            };
        }
    },
    SqlTable {
        @Override
        public Runnable worker(Document doc) {
            return new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread2");
                    // createSQLTable(graphicNode, gUINodeList, eElement);
                }
            };
        }
    },
    DialChart {
        @Override
        public Runnable worker(Document doc) {
            return new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread3");
                    // createDialChart(graphicNode, gUINodeList, dialSpecificNodeList, eElement);
                }
            };
        }
    },
    HourlyDialChart {
        @Override
        public Runnable worker(Document doc) {
            return new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread4");
                    // createHourlyDialChart(graphicNode, gUINodeList, dialSpecificNodeList, eElement);
                }
            };
        }
    };
    public abstract Runnable worker(Document doc);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM