繁体   English   中英

Runnable和ExecutorService的奇怪行为

[英]Odd behavior with Runnable and ExecutorService

我在多线程中遇到了一些非常奇怪的行为。 我有两个类:DipoleTester和Dipole。

DipoleTester尝试创建多个Dipole对象,然后异步运行它们。 问题是DipoleTester只是一次运行所有其Dipole对象,而不是一次运行2个。

这是DipoleTester:

public class DipoleTester {
    public static String DIR = "./save/";
    public static void main(String[] args) throws InterruptedException {
        Dipole trial;
        ExecutorService service = Executors.newFixedThreadPool(2);      

        for (int r = 10; r < 13; r += 1) {
            double radius = (double) r / 10000.0;
            for (int matType = 0; matType < 3; matType++) {
                String name = "Simple_mat"+matType + "_rad" + radius;
                trial = new DipoleSimple(DIR + "Simple/", name);
                trial.materialType = matType;
                trial.RADIUS = radius;
                service.submit(trial);

            }
        }
        service.shutdown();
        service.awaitTermination(100, TimeUnit.HOURS);
    }
}

这是偶极子的(相关位)

public abstract class Dipole implements Runnable{
    ...     
    public void run() {
        initiate();
    }
    public void initiate() {
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date = new Date();
        System.out.println(dateFormat.format(date) + ": Starting: " + NAME);
        model = ModelUtil.create(NAME);
        model.modelNode().create("mod1");
        makeParams();
        makeVariables();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    ...
}

现在的问题是,即使使用thread.sleep(5000),所有线程也会一次执行! 我不知道发生了什么事。 这是控制台输出:

05/08/2013 19:17:31: Starting: Simple_mat0_rad0.001
05/08/2013 19:17:31: Starting: Simple_mat1_rad0.001
05/08/2013 19:17:31: Starting: Simple_mat2_rad0.001
05/08/2013 19:17:31: Starting: Simple_mat0_rad0.0011
05/08/2013 19:17:31: Starting: Simple_mat1_rad0.0011
05/08/2013 19:17:31: Starting: Simple_mat2_rad0.0011
05/08/2013 19:17:31: Starting: Simple_mat0_rad0.0012
05/08/2013 19:17:31: Starting: Simple_mat1_rad0.0012
05/08/2013 19:17:31: Starting: Simple_mat2_rad0.0012

您的Runnable任务在进入Thread.sleep()调用之前引发了异常。 这允许下一个任务开始执行。 所有任务都以如此快的速度连续失败,以至于所有任务似乎同时运行。

首先在run()方法中run()Thread.sleep()的调用,您将看到一次仅运行两个线程。

要检测到此类失败,您需要检查每次调用submit()产生的Future实例。 还有其他方法可以批量提交任务列表并等待它们完成,这可能更适合您的应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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