Runnable和ExecutorService的奇怪行为

时间:2013-05-08 23:23:35

标签: java multithreading runnable executorservice

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

DipoleTester尝试创建几个偶极子对象,然后异步运行它们。问题是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);
    }
}

这是Dipole的(相关位)

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

1 个答案:

答案 0 :(得分:1)

您的Runnable任务在进入Thread.sleep()来电之前会抛出异常。这允许下一个任务开始执行。所有任务都以如此快速的连续失败,所有任务似乎都同时运行。

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

要检测此类失败,您需要examine每次调用submit()后产生的Future实例。批量other methods for submitting a list of tasks并等待它们完成,这可能更适合您的应用。