java并发编程学习笔记之线程池等源码小析

2024-05-09 08:08

本文主要是介绍java并发编程学习笔记之线程池等源码小析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      在java并发编程中,线程池是一个比较重要的点,什么时候需要使用线程池,什么时候不需要使用线程池,看不同的需求,众所周知,新增一个线程是比较耗资源的,因此如果每次新增一个任务就添加一个线程,在分时系统中,这不仅会造成每个线程所获得的执行时间大大降低,同时也会使cpu和内存大大消耗,线程池是一种比较合适的处理办法,一方面缓解资源紧张,一方面又能获得不错的性能,但是,对于批处理作业和耗费资源不是很多的任务,选择线程池不是一个很好地设计办法。

     首先看看两个新的接口,Callable和Future源码如下

     

public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}

    

package java.util.concurrent;
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}

    简而言之,callable接口类似Runnable 接口,其call()方法和Runnable的run()方法很相似,但是Callable有返回值,而Runnable没有返回值。Future保存异步计算的结果。可以启动一个计算,将Future对象交给某个线程,然后忘掉它,也就是当他是一个返回值。

    通常在一般线程中会使用FutureTask类,FutureTask接口继承自RunnableFuture,而Runnable接口继承Runnable和Future。

    首先看下FutureTask的简单用法:

package com.luchi.thread.threadpool;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TestFutureRCallable implements Callable<Integer>{
private int counter=0;
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("i am on the running");
return 1;
}
public  static  void main(String[]args) throws InterruptedException, ExecutionException{
TestFutureRCallable testThread=new TestFutureRCallable();
FutureTask<Integer>futureTask=new FutureTask<Integer>(testThread);
Thread thread=new Thread(futureTask);
thread.start();
System.out.println("future returns:"+futureTask.get());
}
}

      上面程序把Callable的继承类当做FutureTask构造函数参数,然后运行Thread,最后FutureTask能够得到返回值。

      FutureTask有几个构造函数,来看源码

 

     

 public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;       // ensure visibility of callable
}
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
* {@code Future<?> f = new FutureTask<Void>(runnable, null)}
* @throws NullPointerException if the runnable is null
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;       // ensure visibility of callable
}

  一个是FutureTask(Callable callbale),接受Callable对象,另一个是FutureTask(Runnable runnable,V result),接受Runnable对象。但是从源码可以看出,不管是Callable或者是Runnable,FutureTask都将其转化成Callable对象,Executors.callable(runnable, result);这个方法使用了适配器模式,将Runnable对象转换成Callable对象,看一眼源码:

 public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}

   从源码可以看出,适配器将Runnable对象的run方法放在了Callable对象的call接口中

   也就是说,无论是Callable还是Runnable对象,在FutureTask中都是当做Callable对象使用,由于FutureTask继承了Runnable接口,看一眼其实现的run方法

   

  public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}

   其核心就是执行callable对象的call方法,这也和上面的分析对应。

   然后看一眼FutureTask的get方法

   

  public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}

 如果计算没有结束,则阻塞,如果已经完成则返回计算结果

 

 说了这么多,最后来看看线程池。

 首先看下线程池的简单用法:

 

package com.luchi.thread.threadpool;
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;
public class TestThreadPool implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("the thread is running");
return 10;
}
public static void main(String args[]) throws InterruptedException, ExecutionException{
ExecutorService excutor =Executors.newCachedThreadPool();
TestFutureRCallable test=new TestFutureRCallable();
Future<Integer> future=excutor.submit(test);
System.out.println("  "+future.get());
excutor.shutdown();
}
}

 

 

 

 上面的程序中,简单的使用了线程池,常见的获取线程池的方法有两种,一种是 Executors.newCachedThreadPool()一种是Executors.newFixedThreadPool();看一眼两者的源码

 

 

public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

 

   两者都返回了ThreadPoolExecutor对象,ThreadPoolExecutor构造函数的意义简单解释下,第一个和第二个参数指的是线程池中线程的线程数量最小M和最大的值N,第三个是多长时间空闲线程回收,第四个参数是第三个的时间单位,第五个参数是表示使用的阻塞Queue,线程池开设线程的方法如下:

   假如新任务来了,如果当前线程数少于最小的M,则新增一个线程,如果在M~N之间,则把任务丢进等待队列中,如果等待队列满了之后,则再新增一个线程,直到到最大的值N。

   newFixecThreadPool中使用了M值和N值相同,也就是新任务来了会一直增开线程数到M,然后再丢进LinkedBlockingQueue中,LinkedBlockingQueue是一个大小无限的阻塞队列,当然这个无限是相对于当前的资源情况,newCachedThreadPool的线程数是从0到无限个,而SynchronousQueue容量为0,意味着任务来了就新开一个线程?(这里不是很了解,有待研究)

   再来看一下其submit()方法

 

 public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
/**
* @throws RejectedExecutionException {@inheritDoc}
* @throws NullPointerException       {@inheritDoc}
*/
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}

   summit接受Callable和Runnable方法,返回执行的Future对象,本文不去探讨实现细节。

 

这篇关于java并发编程学习笔记之线程池等源码小析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/972852

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.