我有一个应用程序基本上会使用ExecutorService同时运行多个线程,但不知何故它只执行了其中一些。在这个例子中,我将30个任务提交给10个线程的池,但它只执行了大约20个任务。我的代码有什么问题吗?
我已经把一些睡眠时间等待,但仍然没有更好的运气。我应该将它作为ScheduledThreadPool运行吗?
以下是我的代码:
ExecutorService executor = Executors.newFixedThreadPool(10);
for(int i =0;i<30;i++) {
Faker faker = new Faker();
String firstName = faker.name().lastName();
RunningThread run = new RunningThread(firstName.toLowerCase(), s3, gcs, amazonIam, googleIAM, false, projectName, 1);
System.out.println("run thread "+ i);
executor.submit(run);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("\nFinished all threads");
这是Thread实现:
public class RunningThread implements Runnable {
String name;
AmazonS3 s3 ;
Storage gcs;
AmazonIdentityManagement amazonIam ;
Iam googleIAM ;
boolean companyReg;
String projectName;
int employeeType;
public RunningThread( String name, AmazonS3 s3, Storage gcs, AmazonIdentityManagement amazonIam, Iam googleIAM, boolean companyReg, String projectName, int employeeType) {
this.projectName = projectName;
this.name = name;
this.s3 =s3;
this.gcs = gcs;
this.amazonIam = amazonIam;
this.googleIAM = googleIAM;
this.employeeType = employeeType;
this.companyReg = companyReg;
}
@Override
public void run() {
// TODO Auto-generated method stub
long duration = 0;
try {
// long start = System.currentTimeMillis();
if(companyReg == true) {
Thread.sleep(2000);
duration = MainApplication.registerCompany(s3, gcs, amazonIam, googleIAM, name, projectName);
}else {
Thread.sleep(2000);
duration = MainApplication.registerNewCfBEmployee(s3, gcs, amazonIam, googleIAM, name, projectName, employeeType);
}
MainApplication.duration.add(duration);
System.out.println(duration);
Thread.sleep(30000);
} catch (IOException | GeneralSecurityException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
有什么建议吗?