在多线程的场景,如果对一个变量加锁以保证同一时间只有一个线程访问?
1.synchronized
public class SynchronizedExample {
private int counter = 0;
// 使用 synchronized 修饰方法
public synchronized void increment() {
counter++;
}
// 使用 synchronized 修饰代码块
public void incrementWithBlock() {
synchronized (this) {
counter++;
}
}
public int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
SynchronizedExample example = new SynchronizedExample();
// 创建多个线程并发执行
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.increment(); // 或者调用 example.incrementWithBlock()
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
// 等待线程执行完成
thread1.join();
thread2.join();
System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
}
}
2.reentrantlock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private int counter = 0;
private final Lock lock = new ReentrantLock(); // 创建锁对象
public void increment() {
lock.lock(); // 加锁
try {
counter++;
}finally {
lock.unlock(); // 释放锁
}
}
public int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockExample example = new ReentrantLockExample();
// 创建多个线程并发执行
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
// 等待线程执行完成
thread1.join();
thread2.join();
System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
}}
3.使用 AtomicInteger(无锁实现)
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet(); // 原子递增
}
public int getCounter() {
return counter.get();
}
public static void main(String[] args) throws InterruptedException {
AtomicIntegerExample example = new AtomicIntegerExample();
// 创建多个线程并发执行
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
// 等待线程执行完成
thread1.join();
thread2.join();
System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
}
}