多线程 - 为每个循环创建新线程

时间:2015-06-24 17:29:01

标签: java multithreading

我对多线程知之甚少,但我认为它可能对我正在做的事情有用。我有一些东西循环遍历我的xml文件中的每个graphicNode,并根据读取的信息创建一个对象。根据它可以在查询/查询中使用的对象,它将使用存储过程。然后将该对象存储在arrayList中。这最终导致我的程序开始大约一分钟。有没有办法可以在每次循环时创建一个新线程?这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

  

我对多线程知之甚少,但我认为它可能对我正在做的事情有用。

     

这最终导致我的程序花了一分钟才开始

你领先于自己。首先,您应该对代码进行概要分析,以了解您在哪些方面遇到了性能问题。看看VisualVM就可以了。您可能不小心写了一个O(n ^ 2)算法。

  

取决于它可以在查询中使用的对象,或者它将使用存储过程。

我打赌它在这里。连接池或批处理请求可能比直接进入线程更好。

答案 1 :(得分:0)

question解决了类似的问题。

所以基本上你需要为每个任务创建一个新的runnable,下面是一个例子(虽然我没有测试它但会给你一个想法):

  

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

}