本文主要是介绍java通过Executors创建多线程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java 线程池创建多线程
多线程开发,我这里就不说理论直接上代码。
java通过Executors可以创建五种方式的对线程:
第一种: 创建一个单线程。
第二种: 创建一个可变的多线程。:
第三种: 创建一个固定线程数的多线程。
第四种:创建一个定时的多线程。
第五种:创建可以调参数的多线程。
四种线程的创建方式:
//创建固定的线程池executorService = Executors.newFixedThreadPool(THREAD_SIZE);//创建可变线程池executorService = Executors.newCachedThreadPool();//创建单个线程池executorService = Executors.newSingleThreadExecutor();//创建固定时间的线程池executorService = Executors.newScheduledThreadPool(10);//线程池调优int corePoolSize = 2; //核心线程数int maximumPoolSize = 5; //最大线程数long keepAliveTime = 10L; //线程存活时间TimeUnit unit = TimeUnit.SECONDS;executorService = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
package com.util.multithreaduploadfile.util.multiThread;/*** @author :柳浪涛* @packagename:com.util.multithreaduploadfile.util.multiThread* @date :2021/3/24 11:30* @modified By :* @version: 1.0* @Email: llt@echase.cn* @description: 固定线程池操作**/import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;import java.io.BufferedInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;public class FixedThreadPool {private static final Logger log = Logger.getLogger(FixedThreadPool.class);private static final int THREAD_SIZE = 7;public static Map<String, String> unzip(String key) throws Exception {//解压,不支持包含文件夹ZipEntry entry = null;BufferedInputStream bis = null;ExecutorService executorService = null;ConcurrentHashMap<String, String> resultMap = new ConcurrentHashMap<String, String>();try {//创建固定的线程池executorService = Executors.newFixedThreadPool(THREAD_SIZE);CompletionService<String> ecs = new ExecutorCompletionService<String>(executorService);List<Callable<String>> all = new ArrayList<>();for (int i = 0; i < 20; i++) {UploadImage uploadImage = new UploadImage(resultMap, "name" + i, key);Future<String> submit = ecs.submit(uploadImage);SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");all.add(uploadImage);System.out.println("==========前==========" + simple.format(new Date()));//这里发生了阻塞
// System.out.println("==========take==========" +ecs.take().get());System.out.println("==========后==========" + simple.format(new Date()));}System.out.println("=======多线程后面===========");//在这里阻塞//所有的线程执行完了才会执行下面的这里List<Future<String>> futures = executorService.invokeAll(all);if (futures != null && futures.size() > 0) {for (Future<String> future : futures) {System.out.println(future.get());}}System.out.println("=======多线程后面===========");//只有通过execute提交的任务才能将它抛出的异常交给未捕获的异常处理器,// 而通过submit提交的任务,无论是抛出的未检查的异常,还是已检查的异常,//都将被认为是任务返回状态的一部分。如果一个由submit提交的任务由于抛出异常而结束,// 那么这个异常将被Future.get封装在ExecutionException中重新抛出} catch (Exception e) {System.out.println("====== 2 ====== " + e.getMessage());return null;} finally {executorService.shutdown();if (bis != null) {bis.close();}}return resultMap;}static class UploadImage implements Callable<String> {private ConcurrentHashMap resultMap;private String imgName;private byte[] imgBytes;private String key;public UploadImage(ConcurrentHashMap resultMap, String imgName, String key) {this.resultMap = resultMap;this.imgName = imgName;this.key = key;}@Overridepublic String call() {System.out.println();System.out.println("========imgName()======" + imgName);System.out.println("========线程编号======" + Thread.currentThread().getId());Random ran = new Random();try {Thread.sleep(100);} catch (Exception ex) {System.out.println("现场报错" + ex.getMessage());}return imgName;}}public static void main(String[] args) {try {FixedThreadPool.unzip("012");} catch (Exception EX) {System.out.println(String.format("%s%s", "========错误==========", EX.getMessage()));}}
}
对于没有使用过Executors来创建多线程的,这个是一个特别好的例子。
mvn 的pom.xml附件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.util.multi.thread.upload.file</groupId><artifactId>multithread-uploadfile</artifactId><version>0.0.1-SNAPSHOT</version><name>multithread-uploadfile</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version></dependency><!-- log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><!--swagger开始--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><!--swagger结束--><!--<dependency>--><!--<groupId>javax.servlet</groupId>--><!--<artifactId>javax.servlet-api</artifactId>--><!--<version>4.0.1</version>--><!--<scope>provided</scope>--><!--</dependency>--><!-- fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency><!--<dependency>--><!--<groupId>com.fasterxml.jackson.core</groupId>--><!--<artifactId>jackson-databind</artifactId>--><!--<version>2.9.5</version>--><!--</dependency>--><!-- mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><!-- druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.23</version></dependency><dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.10.5</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><dependency><groupId>com.jd.utils</groupId><artifactId>utils-common</artifactId><version>2.0.1.RELEASE</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
这篇关于java通过Executors创建多线程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!