How to crate a list of objects and execute them one by one?
Solution 1:
I would recommend using Executors.newFixedThreadPool
too, but with a try catch statement wrapping it.
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(3);
SomeClass someClass = new SomeClass();
for (int i = 0; i < 10; i++) {
service.submit(someClass); // Here you could also use a lambda instead of implementing the Runnable interface (() -> someClass.sum())
}
finally {
if (service != null) service.shutdown();
}
The example above shows how to use multiple threads to execute your piece of code concurrently, but it is not thread-safe. If you want to have multiple threads executing one by one your sum() method, you could use synchronize in your sum() method signature or inside the try catch block (synchronize(someClass) { for... }
)
There are other features in the Java Concurrency API that can be used for this case. I recommend that you look them up before choosing one, because there are other options that are thread-safe, for example atomic classes, synchronized blocks, the Lock framework and cyclic barriers. But the example above is completely usable.
Solution 2:
Use ThreadPoolExecutor
.
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 1000; i++) {
SomeClass sc = ....;
executor.submit(sc);
}
executor.shutdown();
executor.awaitTermination(100, TimeUnit.HOURS);