0

我在多线程中遇到了一些非常奇怪的行为。我有两个课程: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
4

1 回答 1

1

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

调用Thread.sleep()您在方法中执行的第一件事run(),您将看到一次只运行两个线程。

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

于 2013-05-08T23:43:57.303 回答