Multi-threaded and highly concurrent 8- Thread Pool 1

Executor、 ExecutorService、ThreadPoolExecutor

Executor: define and run threads
ExecutorService: inherited Executor. It extends the executor interface. Realized the statement cycle control thread
ThreadPoolExecutor: Thread Pool

Executor->ExecutorService->ThreadPoolExecutor

Callable

Runnable is used to perform the same as, but callable have a return value, we can not wait for the thread pool.
Usually the joint thread pool and future use, Submit () method passing Callable object, the return value future.
After submit an asynchronous process is not blocked.
Future.get () method is a blocking process, waiting to take the return value

Callable<String> call = new Callable(){
	@Override
	public String call() throws Exception{
		return "hello";
	}
}
ExecutorService service = Executors.newCachedThreadPool();
Future<String> future = service.submit(call);//异步过程
System.out.println(future.get());
service.shutdown();

FutureTask

Either as a task, but also can be used as future. After execution of the task, the return value saved directly to the Future.
(Underlying implementation, FutureTask realized RunnableFuture, RunnableFuture inherits the Runnable and Future)

FutureTask<Integer> task = new FutureTask<>(()->{
	return 1000;
});//等同于runnable,可以直接传入thread,更加灵活
new Thread(task).start();
System.out.println(task.get());//阻塞

CompletableFuture

Multi-task management
executed asynchronously, after waiting for all returned results, or any of the returned results continue

//
CompletableFuture<Double> f1 = CompletableFuture.supplyAsync(()->test1());//异步执行
CompletableFuture<Double> f2 = CompletableFuture.supplyAsync(()->test2());
CompletableFuture<Double> f3 = CompletableFuture.supplyAsync(()->test3());
//所有的的Cfuture执行完毕,再继续执行
CompletableFuture.allof(f1,f2,f3).join();
//有一个的Cfuture执行完毕,再继续执行
CompletableFuture.anyof(f1,f2,f3).join();

ThreadPoolExecutor、ForkJoinPool

ThreadPoolExecutor: common thread pool
ForkJoinPool: Summary task decomposition
can perform many tasks (subtasks) with very little thread, TPE is not possible to perform subtasks
CPU-intensive

ThreadPoolExecutor

The internal structure of the thread pool is two sets. A set of maintenance thread, a set of maintenance tasks.
Statement by hand thread pool Seven Dwarfs

 public ThreadPoolExecutor(int corePoolSize,//核心线程,核心线程一直存活
                              int maximumPoolSize,//最大线程
                              long keepAliveTime,//存活时间,超过存活时间的线程归还OS,直到只剩下核心线程
                              TimeUnit unit,//时间单位
                              BlockingQueue<Runnable> workQueue,//阻塞队列,blockq,传入不同blockq产生不同线程池
                              ThreadFactory threadFactory,//线程工厂生成线程,
                              RejectedExecutionHandler handler)//拒绝策略。核心线程满载,任务队列(Block)满载,最大线程数满载,执行拒绝策略
//ThreadPoolExecutor提供的四种拒绝策略                              
//abort:抛异常
//Discard:扔掉,不抛异常
//DiscardOldest:扔掉排队时间最久的
//CallerRuns:调用线程池线程的线程处理任务    
//自定义拒绝策略,将未处理线程进行存储(redis,kafka,mysql),之后消费者去抓紧处理(实现RejectedExecutionHandler)                   
	//threadfactory
	  public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),//atomic原子类
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);//设置非守护线程
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);//执行级别,普通级别
            return t;
        }
Published 25 original articles · won praise 0 · Views 579

Guess you like

Origin blog.csdn.net/RaymondCoder/article/details/105128432