高级并发编程与并发工具类之重生在deepseek-Java-E先生的博客
Java
MySQL
大数据
Python
前端
黑科技
大语言模型
    首页 >> 互联网 >> Java

高级并发编程与并发工具类之重生在deepseek

[导读]:1. 并发工具类简介Java 提供了丰富的并发工具类,用于简化多线程编程。这些工具类位于java.util.concurrent包中,包括:ExecutorService:线程池管理。CountDownLatch:等待一组线程完成。CyclicBarrier:等待一组线程到达某个屏障点。Semaphore:控制同时访问某个资源的线程数量。Future和Complet...

1. 并发工具类简介

Java 提供了丰富的并发工具类,用于简化多线程编程。这些工具类位于 java.util.concurrent 包中,包括:

  • ExecutorService:线程池管理。

  • CountDownLatch:等待一组线程完成。

  • CyclicBarrier:等待一组线程到达某个屏障点。

  • Semaphore:控制同时访问某个资源的线程数量。

  • Future  CompletableFuture:异步编程。

2. 使用 ExecutorService 管理线程池

ExecutorService 是 Java 提供的线程池管理工具,可以有效地复用线程,减少创建和销毁线程的开销。

2.1 创建线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 提交任务
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("Task is running in thread: " + Thread.currentThread().getName());
            });
        }

        // 关闭线程池
        executor.shutdown();
    }
}

3. 使用 CountDownLatch 等待线程完成

CountDownLatch 用于等待一组线程完成后再执行某个任务。

3.1 使用 CountDownLatch
import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        int n = 3;
        CountDownLatch latch = new CountDownLatch(n);

        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                System.out.println("Thread is running");
                latch.countDown();
            }).start();
        }

        // 等待所有线程完成
        latch.await();
        System.out.println("All threads have finished");
    }
}

4. 使用 CyclicBarrier 同步线程

CyclicBarrier 用于等待一组线程到达某个屏障点后再继续执行。

4.1 使用 CyclicBarrier
import java.util.concurrent.CyclicBarrier;

public class Main {
    public static void main(String[] args) {
        int n = 3;
        CyclicBarrier barrier = new CyclicBarrier(n, () -> {
            System.out.println("All threads have reached the barrier");
        });

        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                System.out.println("Thread is running");
                try {
                    barrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

5. 使用 Semaphore 控制资源访问

Semaphore 用于控制同时访问某个资源的线程数量。

5.1 使用 Semaphore
import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) {
        int permits = 2;
        Semaphore semaphore = new Semaphore(permits);

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("Thread is running");
                    Thread.sleep(1000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

6. 使用 CompletableFuture 进行异步编程

CompletableFuture 是 Java 8 引入的异步编程工具,支持链式调用和组合多个异步任务。

6.1 使用 CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 异步执行任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("Task is running in thread: " + Thread.currentThread().getName());
            return "Hello, World!";
        });

        // 获取任务结果
        String result = future.get();
        System.out.println("Result: " + result);
    }
}

7. 今日任务

  1. 使用 ExecutorService 创建一个线程池,并提交多个任务。

  2. 使用 CountDownLatch 等待一组线程完成后再执行某个任务。

  3. 使用 CyclicBarrier 同步一组线程,并在所有线程到达屏障点后执行某个任务。

  4. 使用 CompletableFuture 实现一个简单的异步任务链。

8. 示例代码

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 任务1:使用 ExecutorService 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("Task is running in thread: " + Thread.currentThread().getName());
            });
        }
        executor.shutdown();

        // 任务2:使用 CountDownLatch 等待线程完成
        int n = 3;
        CountDownLatch latch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                System.out.println("Thread is running");
                latch.countDown();
            }).start();
        }
        latch.await();
        System.out.println("All threads have finished");

        // 任务3:使用 CyclicBarrier 同步线程
        CyclicBarrier barrier = new CyclicBarrier(n, () -> {
            System.out.println("All threads have reached the barrier");
        });
        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                System.out.println("Thread is running");
                try {
                    barrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

        // 任务4:使用 CompletableFuture 实现异步任务链
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("Task is running in thread: " + Thread.currentThread().getName());
            return "Hello, World!";
        });
        String result = future.get();
        System.out.println("Result: " + result);
    }
}

image.png


本文来自E先生的博客,如若转载,请注明出处:https://javajz.cn

留言区

联系人:
手   机:
内   容:
验证码:

历史留言

欢迎加Easy的QQ