|
| 1 | +package multithread.singlevsmultiplethreads; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.concurrent.ExecutionException; |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.Future; |
| 9 | + |
| 10 | +/** |
| 11 | + * This folder has two classes which is a good illustration to show the power of multithreading: |
| 12 | + * it dramatically improves throughput and speeds up workload! |
| 13 | + */ |
| 14 | +public class MultiThreadedApp { |
| 15 | + private static final int THREAD_POOL_SIZE = 5; |
| 16 | + private static final int TOTAL_TASKS = 10; |
| 17 | + private static final int MILLISECONDS_TO_FINISH_A_TASK = 1000; |
| 18 | + |
| 19 | + public static void main(String[] args) throws ExecutionException, InterruptedException { |
| 20 | + |
| 21 | + long start = System.currentTimeMillis(); |
| 22 | + ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); |
| 23 | + List<Future> futures = new ArrayList<>(); |
| 24 | + for (int i = 0; i < TOTAL_TASKS; i++) { |
| 25 | + Runnable worker = new Worker("Worker" + i); |
| 26 | + Future<?> future = executorService.submit(worker); |
| 27 | + futures.add(future); |
| 28 | + } |
| 29 | + executorService.shutdown
8000
span>(); |
| 30 | + while (!executorService.isTerminated()) { |
| 31 | + } |
| 32 | + long end = System.currentTimeMillis(); |
| 33 | + System.out.println("Multi-threaded app finished, it took " + (end - start) / 1000 + |
| 34 | + " seconds for a thread pool of size " + THREAD_POOL_SIZE + " to finish " + |
| 35 | + TOTAL_TASKS + " tasks, with each task takes " + MILLISECONDS_TO_FINISH_A_TASK / 1000 + " seconds."); |
| 36 | + executorService.shutdown(); |
| 37 | + } |
| 38 | + |
| 39 | + static class Worker implements Runnable { |
| 40 | + private String workerName; |
| 41 | + |
| 42 | + public Worker(String workerName) { |
| 43 | + this.workerName = workerName; |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void run() { |
| 48 | + System.out.println(Thread.currentThread().getName() + " starting worker: " + workerName); |
| 49 | + doWork(); |
| 50 | + System.out.println(Thread.currentThread().getName() + " ended for worker: " + workerName); |
| 51 | + } |
| 52 | + |
| 53 | + private void doWork() { |
| 54 | + try { |
| 55 | + Thread.sleep(MILLISECONDS_TO_FINISH_A_TASK); |
| 56 | + } catch (InterruptedException e) { |
| 57 | + throw new RuntimeException(e); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments