think in java - concurrency - Executors

what is Executors?
java

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.socket

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();
	}
}


# shutdownasync

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

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


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();
	}
}


newFixedThreadPoolcode

  1. use bounded number of threads.ci

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

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


# newCachedThreadPool
event

  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.

相關文章
相關標籤/搜索