java 如何实现线程同步
Java 线程同步的实现方法
Java 提供了多种机制来实现线程同步,确保多线程环境下的数据一致性和线程安全。
synchronized 关键字
使用 synchronized 关键字可以修饰方法或代码块,确保同一时间只有一个线程可以访问被保护的资源。
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
}
ReentrantLock 类
ReentrantLock 是 java.util.concurrent.locks 包中的类,提供了比 synchronized 更灵活的锁机制。
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
volatile 关键字
volatile 关键字确保变量的可见性,但不保证原子性。适用于单个变量的简单操作。

public class VolatileExample {
private volatile boolean flag = false;
public void toggleFlag() {
flag = !flag;
}
}
Atomic 类
java.util.concurrent.atomic 包提供了一系列原子类(如 AtomicInteger),适用于无锁的线程安全操作。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
}
CountDownLatch
CountDownLatch 用于让一个或多个线程等待其他线程完成操作。

import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println("Thread running");
latch.countDown();
}).start();
}
latch.await();
System.out.println("All threads completed");
}
}
CyclicBarrier
CyclicBarrier 让一组线程互相等待,达到某个公共屏障点后再继续执行。
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads reached the barrier");
});
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
System.out.println("Thread waiting at barrier");
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore
Semaphore 控制同时访问某个资源的线程数量。
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private final Semaphore semaphore = new Semaphore(3);
public void accessResource() {
try {
semaphore.acquire();
System.out.println("Resource accessed by " + Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
线程安全集合
Java 提供了线程安全的集合类,如 ConcurrentHashMap、CopyOnWriteArrayList 等。
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentCollectionExample {
private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
public void put(String key, Integer value) {
map.put(key, value);
}
}
这些方法可以根据具体需求选择合适的线程同步机制。






