Java高级并发编程
Java高级并发编程
概述
Java高级并发编程提供了更强大的并发工具。本教程介绍Phaser、StampedLock和异步编程。
1. Phaser
import java.util.concurrent.Phaser;
public class PhaserExample {
public static void main(String[] args) {
Phaser phaser = new Phaser(3);
for (int i = 0; i < 3; i++) {
final int taskId = i;
new Thread(() -> {
System.out.println("任务 " + taskId + " 开始");
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务 " + taskId + " 到达屏障");
phaser.arriveAndAwaitAdvance();
System.out.println("任务 " + taskId + " 继续");
}).start();
}
}
}
2. StampedLock
import java.util.concurrent.locks.StampedLock;
public class StampedLockExample {
private final StampedLock lock = new StampedLock();
private int x = 0;
private int y = 0;
public void move(int deltaX, int deltaY) {
long stamp = lock.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
lock.unlockWrite(stamp);
}
}
public int distanceFromOrigin() {
long stamp = lock.tryOptimisticRead();
int currentX = x;
int currentY = y;
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
currentX = x;
currentY = y;
} finally {
lock.unlockRead(stamp);
}
}
return (int) Math.sqrt(currentX * currentX + currentY * currentY);
}
}
3. 实际应用示例
异步编程
import java.util.concurrent.*;
public class AsyncProgramming {
public static void main(String[] args) {
// CompletableFuture
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
});
future.thenApply(s -> s + " World")
.thenAccept(System.out::println);
// 链式操作
CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> 10)
.thenApply(i -> i * 2)
.thenApply(i -> i + 5);
try {
System.out.println("结果: " + result.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
并发数据结构
import java.util.concurrent.*;
public class ConcurrentDataStructures {
public static void main(String[] args) {
// ConcurrentLinkedQueue
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.offer("A");
queue.offer("B");
System.out.println("Queue: " + queue);
// ConcurrentSkipListMap
ConcurrentSkipListMap<Integer, String> sortedMap = new ConcurrentSkipListMap<>();
sortedMap.put(3, "C");
sortedMap.put(1, "A");
sortedMap.put(2, "B");
System.out.println("SortedMap: " + sortedMap);
// ConcurrentSkipListSet
ConcurrentSkipListSet<Integer> sortedSet = new ConcurrentSkipListSet<>();
sortedSet.add(3);
sortedSet.add(1);
sortedSet.add(2);
System.out.println("SortedSet: " + sortedSet);
}
}
并发算法
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ConcurrentAlgorithms {
// 无锁栈
public static class LockFreeStack<T> {
private final AtomicReference<Node<T>> top = new AtomicReference<>();
private static class Node<T> {
final T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
public void push(T data) {
Node<T> newNode = new Node<>(data);
Node<T> currentTop;
do {
currentTop = top.get();
newNode.next = currentTop;
} while (!top.compareAndSet(currentTop, newNode));
}
public T pop() {
Node<T> currentTop;
Node<T> newTop;
do {
currentTop = top.get();
if (currentTop == null) {
return null;
}
newTop = currentTop.next;
} while (!top.compareAndSet(currentTop, newTop));
return currentTop.data;
}
}
public static void main(String[] args) {
LockFreeStack<Integer> stack = new LockFreeStack<>();
for (int i = 0; i < 10; i++) {
stack.push(i);
}
Integer item;
while ((item = stack.pop()) != null) {
System.out.println("弹出: " + item);
}
}
}
4. 最佳实践
- 使用Phaser:替代CyclicBarrier和CountDownLatch
- 使用StampedLock:提高读写锁性能
- 使用CompletableFuture:实现异步编程
- 使用并发集合:提高并发性能
- 使用原子变量:实现无锁算法
总结
Java高级并发编程提供了更强大的并发工具。掌握Phaser、StampedLock和异步编程,可以编写高效的并发程序。