I am new in concurrency in Java, but I have problems in understanding the work of the executor service.
My problem: I'm executing below code separately and I wonder that array of threads faster then executor service (3s vs 30s, by System.currentTimeMillis()).
public class SimpleExample {
private static final int THREAD_COUNT = 10;
private final AtomicInteger cnt;
private SimpleExample() {
cnt = new AtomicInteger();
cnt.set(0);
}
public static void main(String[] args) throws IOException, InterruptedException {
// threads();
// service();
}
private static void threads() throws InterruptedException {
SimpleExample example = new SimpleExample();
ParallelTask task = new ParallelTask(example);
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(task);
}
long a = System.currentTimeMillis();
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("time: " + (System.currentTimeMillis() - a));
}
private static void service() {
SimpleExample example = new SimpleExample();
ParallelTask task = new ParallelTask(example);
ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
long a = System.currentTimeMillis();
Future future = service.submit(task);
while (!future.isDone()) {
// do nothing
}
service.shutdown();
System.out.println("time: " + (System.currentTimeMillis() - a));
}
void run() {
while (cnt.get() < 300) {
try {
Thread.sleep(100);
System.out.println(cnt.get());
cnt.incrementAndGet();
} catch (InterruptedException ignore) {}
}
}
static class ParallelTask implements Runnable {
private final SimpleExample example;
ParallelTask(SimpleExample example) {
this.example = example;
}
@Override
public void run() {
example.run();
}
}
}
How it's possible? Thanks.