java并发如何处理
处理Java并发的方法
使用synchronized关键字
通过synchronized修饰方法或代码块,确保同一时间只有一个线程访问共享资源。适用于简单的同步需求,但可能引发性能问题。
public synchronized void increment() {
count++;
}
使用Lock接口ReentrantLock提供更灵活的锁机制,支持公平锁、可中断锁和超时锁。需手动释放锁,避免死锁。
Lock lock = new ReentrantLock();
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
使用并发集合ConcurrentHashMap、CopyOnWriteArrayList等线程安全集合类,内部通过分段锁或无锁技术实现高效并发。
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
使用原子类AtomicInteger、AtomicLong等基于CAS(Compare-And-Swap)操作,适合无锁化的计数器场景。

AtomicInteger atomicCount = new AtomicInteger(0);
atomicCount.incrementAndGet();
使用线程池
通过ExecutorService管理线程生命周期,避免频繁创建销毁线程的开销。
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task executed"));
executor.shutdown();
使用CountDownLatch/CyclicBarrier
协调多线程的执行顺序。CountDownLatch等待所有子任务完成,CyclicBarrier让线程相互等待至指定状态。
CountDownLatch latch = new CountDownLatch(3);
latch.countDown();
latch.await();
使用Future和CompletableFuture
异步编程模型,Future获取异步结果,CompletableFuture支持链式调用和组合操作。

CompletableFuture.supplyAsync(() -> "Result")
.thenApply(s -> s.toUpperCase())
.thenAccept(System.out::println);
避免死锁
确保锁的获取顺序一致,或使用tryLock超时机制。分析工具如jstack可检测死锁。
if (lock1.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
// 操作资源
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
使用volatile关键字
保证变量的可见性,但不保证原子性。适用于状态标志等简单场景。
private volatile boolean running = true;
ThreadLocal变量
为每个线程维护独立的变量副本,避免共享资源竞争。
ThreadLocal<Integer> threadLocalCount = ThreadLocal.withInitial(() -> 0);
threadLocalCount.set(threadLocalCount.get() + 1);






