Java在循环中实例化一个类

时间:2014-03-31 19:19:22

标签: java multithreading loops object

目前我的代码一个接一个地为多个核实例化一个类,但是我想创建一个循环来实现同时运行的任意数量的核的类detector()。

int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads

    detectors.getStartingConditions(); 

        long startTime = System.currentTimeMillis(); 

        detectors core1= new detectors();
        detectors core2= new detectors();
        detectors core3= new detectors();
        //etc

        core1.start();
        core2.start();
        core3.start();
        //etc

        try 
        { // wait for completion of all thread and then sum
            core1.join();
            core2.join();
            core3.join();
            //etc
        } 
    catch(InterruptedException IntExp) {}         

        long endTime = System.currentTimeMillis();

        System.out.println("That took " + (endTime - startTime) + " milliseconds");

我尝试解决方案:

我按如下方式创建了一个对象数组,但处理器核心依次运行,而不是同时运行。

编辑:核心现在同时运行。

int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads
detectors[] theCores = new detectors[processors];

    detectors.getStartingConditions(); 

        long startTime = System.currentTimeMillis(); 

        for(int i = 0; i <= processors-1; i++){
        theCores[i] = new detectors();
        theCores[i].start();
        }

        for(int i = 0; i <= processors-1; i++){
        try{
        theCores[i].join();}

        catch(InterruptedException IntExp) {} 
        }

        long endTime = System.currentTimeMillis();

        System.out.println("That took " + (endTime - startTime) + " milliseconds");  

1 个答案:

答案 0 :(得分:1)

您的代码在创建下一个线程之前创建线程并加入它。这导致顺序执行。你必须使用两个循环。第一个循环创建所有线程,而第二个循环连接所有线程。

for (int i = 0; i < processors; ++i) {
    theCores[i] = new detectors();
    theCores[i].start();
}

for (int i = 0; i < processors; ++i) {
    try {
        theCores[i].join();
    } catch (InterruptedException ie) {
        RuntimeException re = new RuntimeException("unsupported interruption", ie);
        for (++i; i < processors; ++i) {
            try {
                theCores[i].join();
            } catch (InterruptedException e) {
                re.addSuppressed(e);
            }
        }
        throw re;
    }
}