Java current并发包怎么使用

发布时间:2023-02-22 17:46:40 作者:iii
来源:亿速云 阅读:157

Java current并发包怎么使用

目录

  1. 引言
  2. Java并发包概述
  3. 线程池
  4. 并发集合
  5. 同步工具
  6. 原子变量
  7. 锁机制
  8. Future与Callable
  9. Fork/Join框架
  10. 总结

引言

在现代软件开发中,多线程编程已经成为一种常见的需求。Java作为一种广泛使用的编程语言,提供了丰富的并发编程工具和库。java.util.concurrent包(简称current并发包)是Java并发编程的核心,它提供了线程池、并发集合、同步工具、原子变量、锁机制等多种工具,帮助开发者更高效地处理并发任务。

本文将详细介绍java.util.concurrent包中的主要组件及其使用方法,帮助读者深入理解Java并发编程的核心概念和技巧。

Java并发包概述

java.util.concurrent包是Java 5引入的一个重要的并发编程工具包,它提供了多种并发编程的工具和框架,旨在简化多线程编程的复杂性。该包中的类和接口可以分为以下几类:

接下来,我们将逐一介绍这些组件及其使用方法。

线程池

3.1 Executor框架

Executor框架是Java并发包中用于管理线程池的核心框架。它通过Executor接口及其子接口ExecutorServiceScheduledExecutorService提供了线程池的管理和执行任务的功能。

3.1.1 Executor接口

Executor接口是线程池的基础接口,它定义了一个简单的方法execute(Runnable command),用于执行一个任务。

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Task executed by Executor"));

3.1.2 ExecutorService接口

ExecutorService接口扩展了Executor接口,提供了更丰富的线程池管理功能,如任务提交、线程池关闭等。

ExecutorService executorService = Executors.newFixedThreadPool(5);
executorService.submit(() -> System.out.println("Task submitted to ExecutorService"));
executorService.shutdown();

3.1.3 ScheduledExecutorService接口

ScheduledExecutorService接口扩展了ExecutorService接口,提供了定时任务执行的功能。

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
scheduledExecutorService.schedule(() -> System.out.println("Task scheduled after 5 seconds"), 5, TimeUnit.SECONDS);
scheduledExecutorService.shutdown();

3.2 ThreadPoolExecutor

ThreadPoolExecutorExecutorService接口的一个实现类,它提供了更灵活的线程池配置选项。

3.2.1 核心参数

ThreadPoolExecutor的核心参数包括:

3.2.2 示例

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    2, // corePoolSize
    4, // maximumPoolSize
    60, // keepAliveTime
    TimeUnit.SECONDS, // unit
    new LinkedBlockingQueue<>(10), // workQueue
    Executors.defaultThreadFactory(), // threadFactory
    new ThreadPoolExecutor.AbortPolicy() // handler
);

executor.execute(() -> System.out.println("Task executed by ThreadPoolExecutor"));
executor.shutdown();

3.3 ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutorScheduledExecutorService接口的一个实现类,它提供了定时任务执行的功能。

3.3.1 示例

ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(2);
scheduledExecutor.schedule(() -> System.out.println("Task scheduled after 5 seconds"), 5, TimeUnit.SECONDS);
scheduledExecutor.shutdown();

并发集合

4.1 ConcurrentHashMap

ConcurrentHashMap是线程安全的哈希表实现,它通过分段锁机制实现了高效的并发访问。

4.1.1 示例

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.put("key2", 2);

System.out.println(map.get("key1")); // 输出: 1

4.2 CopyOnWriteArrayList

CopyOnWriteArrayList是线程安全的列表实现,它在写操作时创建一个新的副本,从而避免了读操作的锁竞争。

4.2.1 示例

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item1");
list.add("item2");

System.out.println(list.get(0)); // 输出: item1

4.3 BlockingQueue

BlockingQueue是线程安全的队列实现,它支持阻塞的插入和移除操作。

4.3.1 示例

BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
queue.put("item1");
queue.put("item2");

System.out.println(queue.take()); // 输出: item1

同步工具

5.1 CountDownLatch

CountDownLatch是一个同步工具,它允许一个或多个线程等待其他线程完成操作。

5.1.1 示例

CountDownLatch latch = new CountDownLatch(2);

new Thread(() -> {
    System.out.println("Task 1 completed");
    latch.countDown();
}).start();

new Thread(() -> {
    System.out.println("Task 2 completed");
    latch.countDown();
}).start();

latch.await();
System.out.println("All tasks completed");

5.2 CyclicBarrier

CyclicBarrier是一个同步工具,它允许多个线程在某个屏障点等待,直到所有线程都到达该点。

5.2.1 示例

CyclicBarrier barrier = new CyclicBarrier(3);

new Thread(() -> {
    System.out.println("Thread 1 reached the barrier");
    barrier.await();
    System.out.println("Thread 1 passed the barrier");
}).start();

new Thread(() -> {
    System.out.println("Thread 2 reached the barrier");
    barrier.await();
    System.out.println("Thread 2 passed the barrier");
}).start();

new Thread(() -> {
    System.out.println("Thread 3 reached the barrier");
    barrier.await();
    System.out.println("Thread 3 passed the barrier");
}).start();

5.3 Semaphore

Semaphore是一个同步工具,它通过控制许可证的数量来限制对共享资源的访问。

5.3.1 示例

Semaphore semaphore = new Semaphore(2);

new Thread(() -> {
    semaphore.acquire();
    System.out.println("Thread 1 acquired the semaphore");
    semaphore.release();
}).start();

new Thread(() -> {
    semaphore.acquire();
    System.out.println("Thread 2 acquired the semaphore");
    semaphore.release();
}).start();

5.4 Exchanger

Exchanger是一个同步工具,它允许两个线程在某个点交换数据。

5.4.1 示例

Exchanger<String> exchanger = new Exchanger<>();

new Thread(() -> {
    String data = "Data from Thread 1";
    try {
        String received = exchanger.exchange(data);
        System.out.println("Thread 1 received: " + received);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

new Thread(() -> {
    String data = "Data from Thread 2";
    try {
        String received = exchanger.exchange(data);
        System.out.println("Thread 2 received: " + received);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

原子变量

6.1 AtomicInteger

AtomicInteger是一个原子操作的整数类,它提供了线程安全的整数操作。

6.1.1 示例

AtomicInteger atomicInteger = new AtomicInteger(0);
atomicInteger.incrementAndGet();
System.out.println(atomicInteger.get()); // 输出: 1

6.2 AtomicLong

AtomicLong是一个原子操作的长整数类,它提供了线程安全的长整数操作。

6.2.1 示例

AtomicLong atomicLong = new AtomicLong(0);
atomicLong.incrementAndGet();
System.out.println(atomicLong.get()); // 输出: 1

6.3 AtomicReference

AtomicReference是一个原子操作的引用类,它提供了线程安全的引用操作。

6.3.1 示例

AtomicReference<String> atomicReference = new AtomicReference<>("initial value");
atomicReference.set("new value");
System.out.println(atomicReference.get()); // 输出: new value

锁机制

7.1 ReentrantLock

ReentrantLock是一个可重入的互斥锁,它提供了比synchronized更灵活的锁机制。

7.1.1 示例

ReentrantLock lock = new ReentrantLock();

lock.lock();
try {
    System.out.println("Locked by Thread 1");
} finally {
    lock.unlock();
}

7.2 ReadWriteLock

ReadWriteLock是一个读写锁,它允许多个读操作同时进行,但写操作是独占的。

7.2.1 示例

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

readWriteLock.readLock().lock();
try {
    System.out.println("Read lock acquired by Thread 1");
} finally {
    readWriteLock.readLock().unlock();
}

readWriteLock.writeLock().lock();
try {
    System.out.println("Write lock acquired by Thread 2");
} finally {
    readWriteLock.writeLock().unlock();
}

7.3 StampedLock

StampedLock是一个改进的读写锁,它提供了更高效的锁机制。

7.3.1 示例

StampedLock stampedLock = new StampedLock();

long stamp = stampedLock.writeLock();
try {
    System.out.println("Write lock acquired by Thread 1");
} finally {
    stampedLock.unlockWrite(stamp);
}

stamp = stampedLock.readLock();
try {
    System.out.println("Read lock acquired by Thread 2");
} finally {
    stampedLock.unlockRead(stamp);
}

Future与Callable

8.1 Future

Future表示一个异步计算的结果,它提供了检查计算是否完成、获取计算结果等功能。

8.1.1 示例

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

System.out.println("Future result: " + future.get()); // 输出: 42
executorService.shutdown();

8.2 Callable

Callable是一个可以返回结果的任务接口,它与Runnable类似,但可以返回结果。

8.2.1 示例

Callable<Integer> callable = () -> {
    Thread.sleep(1000);
    return 42;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callable);

System.out.println("Callable result: " + future.get()); // 输出: 42
executorService.shutdown();

8.3 CompletableFuture

CompletableFutureFuture的扩展,它提供了更强大的异步编程功能,如任务组合、异常处理等。

8.3.1 示例

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(1000);
    return 42;
});

future.thenAccept(result -> System.out.println("CompletableFuture result: " + result)); // 输出: 42

Fork/Join框架

9.1 ForkJoinPool

ForkJoinPool是一个用于执行ForkJoinTask的线程池,它适用于并行任务的执行。

9.1.1 示例

ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Integer> task = forkJoinPool.submit(() -> {
    return 42;
});

System.out.println("ForkJoinTask result: " + task.join()); // 输出: 42
forkJoinPool.shutdown();

9.2 RecursiveTask

RecursiveTask是一个可以返回结果的递归任务,它适用于需要递归分解的任务。

9.2.1 示例

class FibonacciTask extends RecursiveTask<Integer> {
    private final int n;

    FibonacciTask(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n <= 1) {
            return n;
        }
        FibonacciTask f1 = new FibonacciTask(n - 1);
        f1.fork();
        FibonacciTask f2 = new FibonacciTask(n - 2);
        return f2.compute() + f1.join();
    }
}

ForkJoinPool forkJoinPool = new ForkJoinPool();
FibonacciTask task = new FibonacciTask(10);
System.out.println("Fibonacci result: " + forkJoinPool.invoke(task)); // 输出: 55
forkJoinPool.shutdown();

9.3 RecursiveAction

RecursiveAction是一个不返回结果的递归任务,它适用于不需要返回结果的任务。

9.3.1 示例

class PrintTask extends RecursiveAction {
    private final int start;
    private final int end;

    PrintTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        if (end - start < 10) {
            for (int i = start; i < end; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        } else {
            int mid = (start + end) / 2;
            PrintTask left = new PrintTask(start, mid);
            PrintTask right = new PrintTask(mid, end);
            left.fork();
            right.compute();
            left.join();
        }
    }
}

ForkJoinPool forkJoinPool = new ForkJoinPool();
PrintTask task = new PrintTask(0, 100);
forkJoinPool.invoke(task);
forkJoinPool.shutdown();

总结

java.util.concurrent包为Java开发者提供了丰富的并发编程工具和框架,帮助开发者更高效地处理多线程任务。通过本文的介绍,读者可以了解到线程池、并发集合、同步工具、原子变量、锁机制、Future与Callable、Fork/Join框架等核心组件的使用方法。掌握这些工具和框架,将有助于开发者在实际项目中更好地处理并发问题,提高程序的性能和可靠性。

在实际开发中,开发者应根据具体需求选择合适的并发工具,并注意线程安全、性能优化等问题。希望本文能为读者在Java并发编程的学习和实践中提供有价值的参考。

推荐阅读:
  1. 讲解Java 哈希表(google 公司的上机题)
  2. java中位运算的使用示例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java current

上一篇:JavaScript中的进制与进制转换是什么

下一篇:Java Servlet怎么实现表白墙

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》