Java并发工具类:高效协作的利器
Java并发工具类:高效协作的利器
概述
Java提供了丰富的并发工具类,如CountDownLatch、CyclicBarrier、Semaphore、CompletableFuture等,帮助开发者实现复杂的并发控制。
1. CountDownLatch
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int taskId = i;
new Thread(() -> {
try {
System.out.println("任务" + taskId + "完成");
} finally {
latch.countDown();
}
}).start();
}
latch.await();
System.out.println("所有任务完成");
}
}
2. CyclicBarrier
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
int parties = 3;
CyclicBarrier barrier = new CyclicBarrier(parties, () -> {
System.out.println("所有线程到达屏障点");
});
for (int i = 0; i < parties; i++) {
final int threadId = i;
new Thread(() -> {
try {
System.out.println("线程" + threadId + "到达屏障点");
barrier.await();
System.out.println("线程" + threadId + "继续执行");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
3. Semaphore
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
private final Semaphore semaphore = new Semaphore(3);
public void accessResource() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "获取资源");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
4. CompletableFuture
import java.util.concurrent.CompletableFuture;
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> result = future1.thenCombine(future2,
(s1, s2) -> s1 + " " + s2);
result.thenAccept(System.out::println);
CompletableFuture.supplyAsync(() -> "100")
.thenApply(Integer::parseInt)
.thenApply(n -> n * 2)
.thenAccept(System.out::println);
}
}
5. Exchanger
import java.util.concurrent.Exchanger;
public class ExchangerDemo {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
new Thread(() -> {
try {
String received = exchanger.exchange("Thread1的数据");
System.out.println("Thread1收到: " + received);
} catch (InterruptedException e) { e.printStackTrace(); }
}).start();
new Thread(() -> {
try {
String received = exchanger.exchange("Thread2的数据");
System.out.println("Thread2收到: " + received);
} catch (InterruptedException e) { e.printStackTrace(); }
}).start();
}
}
最佳实践
- CountDownLatch:等待多个任务完成
- CyclicBarrier:多线程同步到达屏障点
- Semaphore:控制并发访问数量
- CompletableFuture:异步编程和结果组合
- Exchanger:线程间数据交换
总结
Java并发工具类提供了丰富的并发控制机制,掌握这些工具类的使用,可以实现复杂的并发场景。