synchronized 是 Java 中的一个关键字,用于实现线程同步。它可以确保在同一时刻只有一个线程可以访问特定的代码块或方法。以下是一些适用于使用 synchronized 锁的场景:
synchronized 可以确保数据的一致性和完整性。public class SharedResource {
private int counter = 0;
public synchronized void increment() {
counter++;
}
}
synchronized 可以确保线程安全。public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
ArrayList、HashMap 等)时,可以使用 synchronized 包装这些集合,以确保线程安全。public class SynchronizedCollection {
private List<String> list = new ArrayList<>();
public synchronized void add(String item) {
list.add(item);
}
}
synchronized 实现线程安全的计数器。public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
synchronized 确保读写操作的原子性。public class ReadWriteLock {
private int value = 0;
private boolean isWriting = false;
public synchronized void read() {
while (isWriting) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Reading value: " + value);
}
public synchronized void write(int newValue) {
isWriting = true;
value = newValue;
isWriting = false;
notifyAll();
}
}
需要注意的是,synchronized 锁可能会导致性能问题,因为它会阻塞其他线程的执行。在实际应用中,可以根据具体需求选择合适的同步机制,如 ReentrantLock、ReadWriteLock 等。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。