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.

转载于:https://my.oschina.net/u/1242229/blog/283983

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值