Executors类

Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口,ExecutorService继承了Executor

  创建固定数目线程的线程池。
  public static ExecutorService newFixedThreadPool(int nThreads)
  当你线程满了后。别的加进池的线程在队列里。这个队列长度无限。如果只跑一个线程,那么别的线程execute进去的时候。会自动排序的。不用你处理。
  newFixedThreadPool内部有个任务队列,假设线程池里有3个线程,提交了5个任务,那么后两个任务就放在任务队列了,即使前3个任务sleep或者堵塞了,也不会执行后两个任务,除非前三个任务有执行完的
  创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
  public static ExecutorService newCachedThreadPool()
  创建一个单线程化的Executor;就是线程数量为1的fixedThreadPool,如果提交了多个任务,那么这些任务将会排队。每一个任务都会在下一个任务执行之前运行结束。所有的任务都会使用相同的线程
  public static ExecutorService newSingleThreadExecutor()
  创建一个固定长度的线程池。而且以延迟或者定时的方式来执行任务。它和其他线程有点不同的是ScheduledThreadPoolExecutor父接口继承ExecutService
  public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  重要方法:
  1)、scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);  :
  command:执行线程
  initialDelay:初始化延时
  period:两次开始执行最小间隔时间
  unit:计时单位
  注意:如果执行的任务时间大于间隔时间的话它不会单开个线程执行,而且任务结束之后在执行下一个任务;
  
  2)、scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit):
  command:执行线程
  initialDelay:初始化延时
  period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
  unit:计时单位

例子:

public class ExecutorTest {
/*public Executor executor;
public ExecutorService executorService;
Future<String> fu;
Callable<String> call;
CompletionService<String> com;
Executors executors;*/

public static void main(String []ages) throws Exception{
	newFixedThreadPoolTest();
	/*newFixedThreadPoolTest();
	newFixedThreadPoolTest();*/
	newCachedThreadPoolTest();
	newSingleThreadExecutorTest();
	newScheduledThreadPoolTest();
	System.out.println("完成");
}
private static void newFixedThreadPoolTest() throws Exception{
	ExecutorService executor = Executors.newFixedThreadPool(2);
	for (int i = 0; i < 6; i++) {
		final int index = i+1;
		System.out.println("task:"+(i+1));
		Runnable run = new Runnable() {
			@Override
			public void run() {
				System.out.println("thread start " + index);
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("thread end "+ index);
			}
		};
		executor.execute(run);
	}
	
	//Thread.sleep(7000);
	//当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态,以后不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。
	//但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。 与它相似的还有一个shutdownNow(),它通过调用Thread.interrupt来实现线程的立即退出
	executor.shutdown();
	//awaitTermination阻塞当前线程,等待剩余任务执行完,然后继续往下执行。如果不适用await,那么shutdown之后,很可能导致剩余任务得不到执行(整个程序退出),或是执行出现异常
	executor.awaitTermination(7000, TimeUnit.MILLISECONDS);
	System.err.println("完成线程!");
	
}

public static void newCachedThreadPoolTest() throws Exception{
	//如果超过60s没有新的任务线程自己退出
	ExecutorService executorService = Executors.newCachedThreadPool();
	for (int i = 0; i < 6; i++) {
		final int index = i+1;
		Runnable run = new Runnable() {
			
			@Override
			public void run() {
				System.out.println("cached线程池线程start"+index);
				try {
					Thread.sleep(1500);
					System.out.println("cached 线程结束end"+index);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		};	
		executorService.execute(run);
	}
	//如果 不写这个默认60s关闭线程池线程自动关闭
	//executorService.shutdown();
}
public static void newSingleThreadExecutorTest() throws Exception{
	ExecutorService executorService = Executors.newSingleThreadExecutor();
	for (int i = 0; i < 6; i++) {
		final int index = i+1;
		Runnable run =new Runnable() {
			
			@Override
			public void run() {
				System.out.println("SingleThread线程池线程start"+index);
				try {
					Thread.sleep(1500);
					System.out.println("SingleThread 线程结束end"+index);
				} catch (Exception e) {
					e.printStackTrace();
				}					
			}
		};
		executorService.execute(run);
	}
	executorService.shutdown();
}
public static void newScheduledThreadPoolTest() throws Exception{
	ScheduledExecutorService serExecutorService = Executors.newScheduledThreadPool(10);
	int index = 1;
	Runnable run = new Runnable() {			
		@Override
		public void run() {
			System.out.println("scheduled线程Start");
			try {
				Thread.sleep(1500);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	};
	serExecutorService.execute(run);
	//从上面程序运行隔8秒开始执行,没过3秒执行一次
	serExecutorService.scheduleWithFixedDelay(run, 8, 3,TimeUnit.SECONDS);
}
}
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值