【问题标题】:Java instantiating a class in a loopJava在循环中实例化一个类
【发布时间】:2014-03-31 19:19:22
【问题描述】:

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

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 的加入。
  • 谢谢,我会更新帖子并进行更正 - 我认为现在代码可以正常工作,但如果您能检查一下,将不胜感激

标签: java multithreading loops object


【解决方案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;
    }
}

【讨论】:

  • 谢谢,一个小错误,我的错。在第二个循环中是否需要 try and catch 代码?
  • 我现在已将 throws InteruptedException 添加到整个方法中,但捕获它的最佳做法是什么?新解决方案代码中的 catch 语句应该移到哪里?
  • 我添加了正确处理InterruptedException的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2020-12-16
相关资源
最近更新 更多