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