线程如何同步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关键字用于确保变量的可见性,即当一个线程修改了volatile变量时,其他线程能立即看到最新的值。
public class VolatileExample {
private volatile boolean flag = false;
public void toggleFlag() {
flag = !flag;
}
}
原子类
java.util.concurrent.atomic包提供了原子类(如AtomicInteger),这些类通过CAS(Compare-And-Swap)操作实现线程安全。
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);
new Thread(() -> {
latch.countDown();
}).start();
new Thread(() -> {
latch.countDown();
}).start();
new Thread(() -> {
latch.countDown();
}).start();
latch.await();
System.out.println("All threads have finished");
}
}
Semaphore
Semaphore用于控制同时访问特定资源的线程数量。

import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private final Semaphore semaphore = new Semaphore(3);
public void accessResource() throws InterruptedException {
semaphore.acquire();
try {
System.out.println("Resource accessed by " + Thread.currentThread().getName());
} finally {
semaphore.release();
}
}
}
选择同步方法的依据
- 简单性:
synchronized关键字使用简单,适合大多数基本场景。 - 灵活性:
ReentrantLock提供了更多功能,如可中断锁、公平锁等。 - 性能:原子类在高并发场景下性能较好。
- 特定需求:
CountDownLatch和Semaphore适用于特定同步需求。
通过合理选择这些方法,可以有效地实现线程同步,确保多线程程序的正确性和性能。






