-
并发集合:Java 提供了一套并发集合类,如
ConcurrentHashMap
,ConcurrentLinkedQueue
和CopyOnWriteArrayList
等,可以在并发环境下使用,而不需担心线程安全问题。 -
原子变量:
java.util.concurrent.atomic
包提供了一组原子变量类,如AtomicInteger
,AtomicLong
,AtomicReference
等,可以在并发环境下进行线程安全的操作。 -
信号量(Semaphore):如果你需要限制某些资源的并发访问数量,你可能需要研究一下信号量。这是一个可以控制同时访问特定资源的线程数的计数器。
-
CountDownLatch 和 CyclicBarrier:这两个类可以帮助你协调多线程之间的操作,例如,可以使一个线程等待其它线程完成各自的工作后再执行。
-
Callable 和 FutureTask:除了Runnable接口,Java还提供了Callable接口,它允许有返回值的任务。FutureTask 可以将 Callable 任务转换为 Future 对象,从而获取任务的运行结果。
-
线程安全的数据类型:例如
ReentrantLock
、ReentrantReadWriteLock
和StampedLock
。这些工具可以帮助你在处理复杂的并发情况时,保证数据的一致性。 -
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 timetry {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 fornew 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 finishSystem.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;}@Overrideprotected 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));}
}