think in java - concurrency - Executors

what is Executors?

java.util.concurrent.Executors simplify concurrent programing by managing Thread objects for you. It allows you to manage the execition of asynchronous tasks without having to explicitly manage the lifecycle of threads.

public class CachedThreadPool {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			pool.execute(new LiftOff());
		}
		pool.shutdown();
	}
}


# shutdown

  1. prevent new tasks from being submitted to that Executor.

  2. current thread will continue to run all existing tasks.


public class FixedThreadPool {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 5; i++) {
			pool.execute(new LiftOff());
		}
		pool.shutdown();
	}
}


newFixedThreadPool

  1. use bounded number of threads.

  2. we do EXPENSIVE thread allocation ONCE, up front.

  3. save time for systems such as event-driven ones which require threads that can be serviced ASAP.


# newCachedThreadPool

  1. create as many threads as it needs during the execution of a program.

  2. a reasonable first choice as an Executor.

public class SingleThreadExecutor {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 5; i++) {
			pool.execute(new LiftOff());
		}
		pool.shutdown();
	}
}

# newSingleThreadExecutor

  1. useful if you want  to run a task continually(long-lived task, eg: listening to incoming socket connection).

  2. if > 1 task is submitted to s SingleThreadExecutor, they will be queued, all using the smae thread.

你可能感兴趣的:(think in java - concurrency - Executors)