在Java中,当多个线程同时访问共享资源时,为了防止数据不一致或损坏的问题,需要进行线程同步。Java提供了多种线程同步的方式,以下是一些常见的方法:
1. 使用synchronized
关键字
synchronized
关键字可以修饰方法或代码块,确保同一时刻只有一个线程可以执行该段代码。
-
同步方法:
public class Counter { private int count = 0; public synchronized void increment() { count++; // 当一个线程访问这个方法时,其他线程必须等待 } public synchronized int getCount() { return count; } }
-
同步代码块:
public class Counter { private int count = 0; private final Object lock = new Object(); public void increment() { synchronized(lock) { count++; // 只有获得lock对象的锁的线程才能执行这个代码块 } } }
2. 使用ReentrantLock
ReentrantLock
是java.util.concurrent.locks
包中的一个类,提供了比synchronized
更灵活的锁定机制。
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock(); // 获取锁
try {
count++;
} finally {
lock.unlock(); // 释放锁
}
}
}
3. 使用volatile
关键字
volatile
关键字确保对变量的读写操作都直接在主内存中进行,从而保证了变量的可见性。虽然volatile
不提供原子性,但它在某些情况下可以用来确保线程安全。
public class Flag {
private volatile boolean flag = false;
public void setTrue() {
flag = true; // 对flag的写操作对其他线程立即可见
}
public boolean check() {
return flag; // 对flag的读操作直接从主内存进行
}
}
4. 使用原子类
Java的java.util.concurrent.atomic
包提供了一组原子类,用于在单个操作中执行复合操作,保证了操作的原子性。
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet(); // 原子地增加count的值
}
public int getCount() {
return count.get();
}
}
5. 使用wait()
和notify()
方法
这两个方法定义在Object
类中,用于线程间的协作。
public class Message {
private String content;
private boolean empty = true;
public synchronized String take() {
while (empty) {
try {
wait(); // 等待content被设置
} catch (InterruptedException e) {}
}
empty = true;
notifyAll(); // 通知其他线程content已被取走
return content;
}
public synchronized void put(String content) {
while (!empty) {
try {
wait(); // 等待content被取走
} catch (InterruptedException e) {}
}
empty = false;
this.content = content;
notifyAll(); // 通知其他线程新的content已设置
}
}
以上是Java中几种常见的线程同步方式。其实选择哪一种方式还是取决于具体的需求和场景。在设计并发程序时,需要仔细考虑数据的一致性、死锁的可能性以及性能影响,以实现高效且安全的并发控制。