java如何线程同步
Java线程同步方法
使用synchronized关键字
synchronized可用于方法或代码块,确保同一时间只有一个线程能访问被保护的资源。实例方法锁的是当前对象,静态方法锁的是类对象。
public synchronized void increment() {
// 线程安全代码
}
public void increment() {
synchronized(this) {
// 线程安全代码块
}
}
使用ReentrantLock
java.util.concurrent.locks.ReentrantLock提供更灵活的锁机制,支持公平锁、可中断锁和超时锁。
private final ReentrantLock lock = new ReentrantLock();
public void performTask() {
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
}
使用volatile变量
volatile保证变量的可见性,确保所有线程都能看到最新值,但不保证原子性。
private volatile boolean flag = false;
使用原子类
java.util.concurrent.atomic包提供原子变量类,如AtomicInteger,保证单个变量的原子操作。

private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
使用CountDownLatch
适用于让多个线程等待直到某个操作完成。
CountDownLatch latch = new CountDownLatch(3);
// 工作线程
latch.countDown();
// 主线程
latch.await();
使用CyclicBarrier
允许多个线程互相等待,到达屏障点后继续执行。
CyclicBarrier barrier = new CyclicBarrier(3);
public void run() {
// 执行任务
barrier.await();
}
使用Semaphore
控制同时访问特定资源的线程数量。

Semaphore semaphore = new Semaphore(5);
public void accessResource() throws InterruptedException {
semaphore.acquire();
try {
// 使用资源
} finally {
semaphore.release();
}
}
使用线程安全集合
java.util.concurrent包提供线程安全集合类,如ConcurrentHashMap、CopyOnWriteArrayList等。
Map<String, String> map = new ConcurrentHashMap<>();
使用ThreadLocal
为每个线程创建变量的独立副本,避免共享。
private ThreadLocal<Integer> threadLocalCount = ThreadLocal.withInitial(() -> 0);
public void increment() {
threadLocalCount.set(threadLocalCount.get() + 1);
}
使用wait/notify机制
基于Object类的wait()和notify()/notifyAll()方法实现线程间通信。
synchronized(lock) {
while(conditionNotMet) {
lock.wait();
}
// 执行操作
lock.notifyAll();
}
选择同步方法时应根据具体场景考虑性能、复杂度和功能需求。synchronized简单但性能较低,ReentrantLock更灵活但需要手动释放锁,高级并发工具适用于复杂同步场景。






