有哪些更复杂的并发编程概念可以进一步学习?

  1. 并发集合:Java 提供了一套并发集合类,如 ConcurrentHashMapConcurrentLinkedQueue 和 CopyOnWriteArrayList 等,可以在并发环境下使用,而不需担心线程安全问题。

  2. 原子变量java.util.concurrent.atomic 包提供了一组原子变量类,如 AtomicIntegerAtomicLongAtomicReference 等,可以在并发环境下进行线程安全的操作。

  3. 信号量(Semaphore):如果你需要限制某些资源的并发访问数量,你可能需要研究一下信号量。这是一个可以控制同时访问特定资源的线程数的计数器。

  4. CountDownLatch 和 CyclicBarrier:这两个类可以帮助你协调多线程之间的操作,例如,可以使一个线程等待其它线程完成各自的工作后再执行。

  5. Callable 和 FutureTask:除了Runnable接口,Java还提供了Callable接口,它允许有返回值的任务。FutureTask 可以将 Callable 任务转换为 Future 对象,从而获取任务的运行结果。

  6. 线程安全的数据类型:例如 ReentrantLockReentrantReadWriteLock 和 StampedLock。这些工具可以帮助你在处理复杂的并发情况时,保证数据的一致性。

  7. Fork/Join 框架:这个框架可以帮助你并行的执行任务,利用多核处理器的优势,提高 java 程序的性能。

以下为Java示例:

       并发集合(ConcurrentHashMap):

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        map.forEach((k, v) -> System.out.println(k + " = " + v));
    }
}

原子变量(AtomicInteger):

import java.util.concurrent.atomic.*;

public class Main {
  public static void main(String[] args) {
    AtomicInteger atomicInt = new AtomicInteger(0);
    atomicInt.incrementAndGet();
    System.out.println(atomicInt); //Prints 1
  }
}

信号量(Semaphore):

import java.util.concurrent.*;

public class Main {
  public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(1); // Only one thread can acquire at a time
    try {
      semaphore.acquire();
      // critical section here
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      semaphore.release(); // release the permit
    }
  }
}

CountDownLatch:

import java.util.concurrent.*;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(3); // three threads to wait for

    new Thread(() -> { System.out.println("Thread 1 finished"); latch.countDown(); }).start();
    new Thread(() -> { System.out.println("Thread 2 finished"); latch.countDown(); }).start();
    new Thread(() -> { System.out.println("Thread 3 finished"); latch.countDown(); }).start();

    latch.await(); // wait for all three threads to finish
    System.out.println("All threads finished"); // print after all threads have finished
  }
}

Callable 和 FutureTask:

import java.util.concurrent.*;

public class Main {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    Callable<Integer> task = () -> {
      TimeUnit.SECONDS.sleep(1);
      return 123;
    };
    FutureTask<Integer> futureTask = new FutureTask<>(task);
    new Thread(futureTask).start();
    System.out.println("futureTask.get() = " + futureTask.get()); // Will output: futureTask.get() = 123
  }
}

线程安全的数据类型(ReentrantLock):

import java.util.concurrent.locks.*;

public class Counter {
    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            count--;
        } finally {
            lock.unlock();
        }
    }

    public int value() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
}

Fork/Join 框架:

import java.util.concurrent.*;

class SimpleRecursiveTask extends RecursiveTask<Integer> {

    private int simulatedWork;

    public SimpleRecursiveTask(int simulatedWork) {
        this.simulatedWork = simulatedWork;
    }

    @Override
    protected Integer compute() {

        if(simulatedWork > 100) {

            System.out.println("Parallel execution and split task : " + simulatedWork);

            SimpleRecursiveTask simpleRecursiveTask1 = new SimpleRecursiveTask(simulatedWork/2);
            SimpleRecursiveTask simpleRecursiveTask2 = new SimpleRecursiveTask(simulatedWork/2);

            simpleRecursiveTask1.fork();
            simpleRecursiveTask2.fork();

            int solution = 0;
            solution = solution + simpleRecursiveTask1.join();
            solution = solution + simpleRecursiveTask2.join();

            return solution;

        } else {
            System.out.println("No need for parallel execution, sequential algorithm is ok. " + simulatedWork);
            return 2 * simulatedWork;
        }
    }
}

public class Main {
    public static void main(String[] args) {

        ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
        SimpleRecursiveTask simpleRecursiveAction = new SimpleRecursiveTask(120);

        System.out.println(forkJoinPool.invoke(simpleRecursiveAction));
    }
}

相关推荐

  1. 哪些复杂并发编程概念可以进一步学习

    2024-04-13 15:40:03       22 阅读
  2. [AIGC]并发编程需要学习哪些知识

    2024-04-13 15:40:03       46 阅读
  3. 目标检测基本概念哪些

    2024-04-13 15:40:03       14 阅读
  4. 人工智能常用编程语言哪些

    2024-04-13 15:40:03       14 阅读
  5. C#-并行编程概念及其运用

    2024-04-13 15:40:03       45 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-13 15:40:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-13 15:40:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-13 15:40:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-13 15:40:03       20 阅读

热门阅读

  1. 数据结构----堆 和 堆排序 代码

    2024-04-13 15:40:03       15 阅读
  2. Qt Designer 如何添加自己制作的控件?

    2024-04-13 15:40:03       15 阅读
  3. C++Qt中异常处理try-catch

    2024-04-13 15:40:03       14 阅读
  4. MATLAB入门介绍

    2024-04-13 15:40:03       15 阅读
  5. C++力扣Leetcode算法5--搜索

    2024-04-13 15:40:03       13 阅读
  6. Dockerfile中 CMD和ENTRYPOINT的区别

    2024-04-13 15:40:03       15 阅读
  7. 【SSH】群晖开启ssh访问

    2024-04-13 15:40:03       13 阅读
  8. 蓝桥杯抱佛脚篇~

    2024-04-13 15:40:03       10 阅读
  9. 从输入URL到页面发生了什么

    2024-04-13 15:40:03       22 阅读
  10. 负载均衡原理及算法

    2024-04-13 15:40:03       20 阅读