线程池的体系结构举例

package com.atguigu.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*

  • 一、线程池:维护了一个线程队列,队列中有多个处于等待状态的线程,避免了每次新建与销毁线程的额外开销,提高了相应速度。
  • 二、线程池的体系结构
  • java.util.concurrent.Executor : 线程池与线程调度的根接口
  •  |-- ** java.util.concurrent.ExecutorService : 线程池的根接口
    
  •  	|-- java.util.concurrent.ThreadPoolExecutor : 线程池的实现类
    
  •  	|-- java.util.concurrent.ScheduledExecutorService : 线程调度的子接口
    
  •  		|--java.util.concurrent.ScheduledThreadPoolExecutor : 继承了 ThreadPoolExecutor, 实现了 ScheduledExecutorService
    
  • 三、java.util.concurrent.Executors 工具类
  • ExecutorService newCachedThreadPool() : 缓存线程池,可根据实际应用,自动的分配线程个数
  • ExecutorService newFixedThreadPool() : 固定大小的线程池
  • ExecutorService newSingleThreadExecutor() : 只有一个线程的线程池
  • ScheduledExecutorService newScheduledThreadPool(int corePoolSize) : 线程调度的线程池,可以延迟或定时执行任务
    */

public class TestThreadPool {

	public static void main(String[] args) throws Exception {
		ExecutorService pool = Executors.newFixedThreadPool(5);
	
	List<Future<Integer>> list = new ArrayList<>();
	
	for (int i = 0; i < 10; i++) {
		Future<Integer> future = pool.submit(new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {
				int num = (int)(Math.random() * 101);
				System.out.println(Thread.currentThread().getName() + ":" + num);
				return num;
			}
		});
		
		list.add(future);
	}
	
	pool.shutdown();
	
	for (Future<Integer> future : list) {
		System.out.println(future.get());
	}
	
	/*ThreadPoolDemo tp = new ThreadPoolDemo();
	
	//创建数量为 5 的线程池
	ExecutorService pool = Executors.newFixedThreadPool(10);
	
	//分配任务
	for (int i = 0; i < 10; i++) {
		pool.submit(tp);
	}
	
	//释放资源
	pool.shutdown();*/
}

/*
 * new Thread(tp).start();
 * new Thread(tp).start();
 */

}

class ThreadPoolDemo implements Runnable{

private int i = 0;

@Override
public void run() {
	
	while(i <= 100){
		System.out.println(Thread.currentThread().getName() + ":" + i++);
	}
	
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值