Commit 0090f997 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Trying out thread pools.

parent 6fa08a97
Loading
Loading
Loading
Loading
+21 −0
Changes for src/main/java/ch15/RunThreads.java: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
package ch15;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunThreads {

  public static void main(String[] args) {
    ExecutorService threadPool = Executors.newFixedThreadPool(2);
    threadPool.execute(() -> run("Job 1"));
    threadPool.execute(() -> run("Job 2"));
    threadPool.shutdown();
  }

  public static void run(String jobName) {
    for (int i = 0; i < 25; i++) {
      String threadName = Thread.currentThread().getName();
      System.out.println(jobName + " is running on thread " + threadName);
    }
  }
}
 No newline at end of file
+36 −0
Changes for src/main/java/ch15/ThreadPools.java: 36 added lines, 0 removed lines.
Original line number Diff line number Diff line
package ch15;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPools {

  public static void main(String[] args) {
    createCachedThreadPool();
  }

  private static void createCachedThreadPool() {
    ExecutorService threadPool = Executors.newCachedThreadPool();
    threadPool.execute(() -> run("Job 1"));
    threadPool.execute(() -> run("Job 2"));
    threadPool.execute(() -> run("Job 3"));
    threadPool.execute(() -> run("Job 4"));
    threadPool.shutdown();
  }

  private static void createFixedThreadPoolWithMoreJobsThanThreads() {
    ExecutorService threadPool = Executors.newFixedThreadPool(2);
    threadPool.execute(() -> run("Job 1"));
    threadPool.execute(() -> run("Job 2"));
    threadPool.execute(() -> run("Job 3"));
    threadPool.execute(() -> run("Job 4"));
    threadPool.shutdown();
  }

  public static void run(String jobName) {
    for (int i = 0; i < 25; i++) {
      String threadName = Thread.currentThread().getName();
      System.out.println(jobName + " is running on thread " + threadName);
    }
  }
}
 No newline at end of file