• java线程池并发实现代码模板


    ThreadPoolExecutor,execute,Runnable

    线程池执行无返回值线程(无需知道执行结果)

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.concurrent.ArrayBlockingQueue;
    4. import java.util.concurrent.ThreadPoolExecutor;
    5. import java.util.concurrent.TimeUnit;
    6. public class ThreadPoolExecuteTemplate {
    7. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    8. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    9. public void doSomething() {
    10. for (int i = 0; i < 10; i++) {
    11. executorService.execute(new Runnable() {
    12. @Override
    13. public void run() {
    14. System.out.println(Thread.currentThread().getName());
    15. }
    16. });
    17. }
    18. System.out.println("over");
    19. }
    20. public static void main(String[] args) {
    21. new ThreadPoolExecuteTemplate().doSomething();
    22. }
    23. }

    线程池执行无返回值线程(需要知道执行结果)

    一般主线程不会等线程并发执行完,所以需要用到其他工具

    CountDownLatch(运行结果放入HashMap)

    ThreadTask.java

    1. package codeTemplate.thread;
    2. import java.util.Map;
    3. import java.util.concurrent.CountDownLatch;
    4. public class ThreadTask implements Runnable {
    5. private final String param;
    6. private final CountDownLatch latch;
    7. private Map result;
    8. public ThreadTask(Map result, String param, CountDownLatch latch) {
    9. this.result = result;
    10. this.param = param;
    11. this.latch = latch;
    12. }
    13. @Override
    14. public void run() {
    15. try {
    16. System.out.println(Thread.currentThread().getName());
    17. result.put(param, param + "over");
    18. } finally {
    19. latch.countDown();
    20. }
    21. }
    22. }

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.Arrays;
    4. import java.util.HashMap;
    5. import java.util.List;
    6. import java.util.Map;
    7. import java.util.concurrent.ArrayBlockingQueue;
    8. import java.util.concurrent.CountDownLatch;
    9. import java.util.concurrent.ThreadPoolExecutor;
    10. import java.util.concurrent.TimeUnit;
    11. public class CountDownLatchTemplate {
    12. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    13. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    14. public void doSomethingNeedResult() {
    15. try {
    16. Map result = new HashMap<>();
    17. List params = Arrays.asList("1", "2", "3", "4", "5");
    18. CountDownLatch latch = new CountDownLatch(params.size());
    19. for (String param : params) {
    20. executorService.execute(new ThreadTask(result, param, latch));
    21. }
    22. latch.await(10, TimeUnit.MINUTES);
    23. System.out.println(result);
    24. } catch (InterruptedException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. public static void main(String[] args) {
    29. new CountDownLatchTemplate().doSomethingNeedResult();
    30. }
    31. }

    CountDownLatch(运行结果放入LIst,不用保持原有顺序)

    ThreadResultToListTask.java

    1. package codeTemplate.thread;
    2. import java.util.List;
    3. import java.util.Random;
    4. import java.util.concurrent.CountDownLatch;
    5. import java.util.concurrent.TimeUnit;
    6. public class ThreadResultToListTask implements Runnable {
    7. private final String param;
    8. private final CountDownLatch latch;
    9. private List result;
    10. public ThreadResultToListTask(List result, String param, CountDownLatch latch) {
    11. this.result = result;
    12. this.param = param;
    13. this.latch = latch;
    14. }
    15. @Override
    16. public void run() {
    17. try {
    18. int randomNumber = new Random().nextInt(3);
    19. System.out.println(Thread.currentThread().getName()+"------------"+randomNumber);
    20. TimeUnit.SECONDS.sleep(randomNumber);
    21. System.out.println(Thread.currentThread().getName()+"------------"+randomNumber);
    22. result.add(param + "over");
    23. } catch (InterruptedException e) {
    24. e.printStackTrace();
    25. } finally {
    26. latch.countDown();
    27. }
    28. }
    29. }

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.*;
    4. import java.util.concurrent.ArrayBlockingQueue;
    5. import java.util.concurrent.CountDownLatch;
    6. import java.util.concurrent.ThreadPoolExecutor;
    7. import java.util.concurrent.TimeUnit;
    8. public class CountDownLatchTemplate {
    9. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    10. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    11. public void doSomethingNeedListResult() {
    12. try {
    13. List result = new ArrayList<>();
    14. List params = Arrays.asList("1", "2", "3", "4", "5");
    15. CountDownLatch latch = new CountDownLatch(params.size());
    16. for (String param : params) {
    17. executorService.execute(new ThreadResultToListTask(result, param, latch));
    18. }
    19. latch.await(10, TimeUnit.MINUTES);
    20. System.out.println(result);
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. }
    25. public static void main(String[] args) {
    26. new CountDownLatchTemplate().doSomethingNeedListResult();
    27. }
    28. }

    CountDownLatch(运行结果需要保持原有顺序)

    ThreadResultHoldOrderTask.java

    1. package codeTemplate.thread;
    2. import java.util.List;
    3. import java.util.Random;
    4. import java.util.concurrent.CountDownLatch;
    5. import java.util.concurrent.TimeUnit;
    6. public class ThreadResultHoldOrderTask implements Runnable{
    7. private final List params;
    8. private final CountDownLatch latch;
    9. private final int index;
    10. public ThreadResultHoldOrderTask(List params,int index, CountDownLatch latch) {
    11. this.params = params;
    12. this.latch = latch;
    13. this.index=index;
    14. }
    15. @Override
    16. public void run() {
    17. try {
    18. int randomNumber = new Random().nextInt(3);
    19. System.out.println(Thread.currentThread().getName()+"------------"+randomNumber);
    20. TimeUnit.SECONDS.sleep(randomNumber);
    21. System.out.println(Thread.currentThread().getName()+"------------"+randomNumber);
    22. params.set(index,params.get(index)+"over");
    23. } catch (InterruptedException e) {
    24. e.printStackTrace();
    25. } finally {
    26. latch.countDown();
    27. }
    28. }
    29. }

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.*;
    4. import java.util.concurrent.ArrayBlockingQueue;
    5. import java.util.concurrent.CountDownLatch;
    6. import java.util.concurrent.ThreadPoolExecutor;
    7. import java.util.concurrent.TimeUnit;
    8. public class CountDownLatchTemplate {
    9. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    10. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    11. public void doSomethingNeedOrderListResult() {
    12. try {
    13. List params = Arrays.asList("1", "2", "3", "4", "5");
    14. CountDownLatch latch = new CountDownLatch(params.size());
    15. for (int i = 0; i < params.size(); i++) {
    16. executorService.execute(new ThreadResultHoldOrderTask(params, i, latch));
    17. }
    18. latch.await(10, TimeUnit.MINUTES);
    19. System.out.println(params);
    20. } catch (InterruptedException e) {
    21. e.printStackTrace();
    22. }
    23. }
    24. public static void main(String[] args) {
    25. new CountDownLatchTemplate().doSomethingNeedOrderListResult();
    26. }
    27. }

    信号量(实现多线程对公共资源的并发访问控制)

    无需知道执行结果

    SemaphoreTask.java

    1. package codeTemplate.thread;
    2. import java.util.concurrent.Semaphore;
    3. import java.util.concurrent.TimeUnit;
    4. import java.util.concurrent.atomic.AtomicInteger;
    5. public class SemaphoreTask implements Runnable {
    6. private final Semaphore semaphore;
    7. private AtomicInteger resource;
    8. public SemaphoreTask(Semaphore semaphore, AtomicInteger resource) {
    9. this.semaphore = semaphore;
    10. this.resource = resource;
    11. }
    12. @Override
    13. public void run() {
    14. try {
    15. semaphore.acquire();
    16. TimeUnit.SECONDS.sleep(3);
    17. System.out.println(Thread.currentThread().getName() + "-------------" + resource.incrementAndGet());
    18. } catch (InterruptedException e) {
    19. e.printStackTrace();
    20. } finally {
    21. semaphore.release();
    22. }
    23. }
    24. }

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.concurrent.ArrayBlockingQueue;
    4. import java.util.concurrent.Semaphore;
    5. import java.util.concurrent.ThreadPoolExecutor;
    6. import java.util.concurrent.TimeUnit;
    7. import java.util.concurrent.atomic.AtomicInteger;
    8. public class SemaphoreTemplate {
    9. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    10. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    11. public void doSomething() {
    12. Semaphore semaphore = new Semaphore(3);
    13. AtomicInteger resource = new AtomicInteger();
    14. for (int i = 0; i < 10; i++) {
    15. executorService.execute(new SemaphoreTask(semaphore, resource));
    16. }
    17. }
    18. public static void main(String[] args) {
    19. new SemaphoreTemplate().doSomething();
    20. }
    21. }

    需知道执行结果

    SemaphoreResultTask.java

    1. package codeTemplate.thread;
    2. import java.util.List;
    3. import java.util.concurrent.CountDownLatch;
    4. import java.util.concurrent.Semaphore;
    5. import java.util.concurrent.TimeUnit;
    6. public class SemaphoreResultTask implements Runnable{
    7. private final Semaphore semaphore;
    8. private final CountDownLatch latch;
    9. private final List params;
    10. private final int index;
    11. public SemaphoreResultTask(Semaphore semaphore, CountDownLatch latch, List params,int index) {
    12. this.semaphore=semaphore;
    13. this.latch = latch;
    14. this.params = params;
    15. this.index = index;
    16. }
    17. @Override
    18. public void run() {
    19. try{
    20. semaphore.acquire();
    21. params.set(index, params.get(index) + " over");
    22. TimeUnit.SECONDS.sleep(1);
    23. System.out.println("in task: "+params);
    24. semaphore.release();
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. }finally {
    28. latch.countDown();
    29. }
    30. }
    31. }

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.Arrays;
    4. import java.util.List;
    5. import java.util.concurrent.*;
    6. import java.util.concurrent.atomic.AtomicInteger;
    7. public class SemaphoreTemplate {
    8. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    9. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    10. public void doSomethingNeedResult() {
    11. try {
    12. List params = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
    13. CountDownLatch latch = new CountDownLatch(params.size());
    14. Semaphore semaphore = new Semaphore(3);
    15. for (int i = 0; i < params.size(); i++) {
    16. executorService.execute(new SemaphoreResultTask(semaphore, latch, params, i));
    17. }
    18. latch.await(10, TimeUnit.MINUTES);
    19. System.out.println("result: "+params);
    20. } catch (InterruptedException e) {
    21. e.printStackTrace();
    22. }
    23. }
    24. public static void main(String[] args) {
    25. new SemaphoreTemplate().doSomethingNeedResult();
    26. }
    27. }

    ThreadPoolExecutor,submit,Callable,Future

    使用

    1. package codeTemplate.thread;
    2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import java.util.Random;
    6. import java.util.concurrent.*;
    7. public class ThreadPoolSubmitCallTemplate {
    8. private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 30, TimeUnit.SECONDS,
    9. new ArrayBlockingQueue<>(100), new ThreadFactoryBuilder().setNameFormat("basic-thread-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
    10. public static Map> sessionMap = new HashMap<>();
    11. public void doSomething(String index) {
    12. Future future = executorService.submit(new Callable() {
    13. @Override
    14. public String call() throws Exception {
    15. TimeUnit.SECONDS.sleep(new Random().nextInt(5));
    16. return "ok";
    17. }
    18. });
    19. sessionMap.put(index, future);
    20. }
    21. public static void main(String[] args) throws ExecutionException, InterruptedException {
    22. ThreadPoolSubmitCallTemplate submitCallTemplate = new ThreadPoolSubmitCallTemplate();
    23. for (int i = 0; i < 10; i++) {
    24. submitCallTemplate.doSomething("session-" + i);
    25. }
    26. System.out.println(sessionMap.get("session-7").get());
    27. }
    28. }

  • 相关阅读:
    如何解除Mac系统文件的隐藏状态?
    IDEA jar看不到反编译后的源码(只有方法那一级/* compiled code*/)
    图书管理系统
    Pyhon函数定义中的:必选参数、可选参数、可变参数
    7天学完Spring:Spring框架搭建和解析以及Bean对象的创建
    携号转网查询易语言代码
    使用Springboot开发前后端分离校园智能出行拼车系统
    【MySQL】索引和事物
    k8s--基础--26.6--监控告警系统--kube-state-metrics
    C/C++ const相关 常量指针 常指针 常指针常量 顶层底层const
  • 原文地址:https://blog.csdn.net/jsq916/article/details/126435767