线程允许无数活动同时发生。
并发编程比单线程编程更困难,因为很多事情都可能出错,而且故障很难重现。你无法避免竞争。它是平台固有的,也是从现在无处不在的多核处理器获得良好性能的要求。本章提供的建议可帮助您编写清晰、正确且文档齐全的并发程序。
1。共享可变数据同步的重要性
- 使用synchronized关键字进行同步保证:
- 互斥:同一时间只有一个线程可以执行同步块。
- 可见性:一个线程所做的更改对其他线程可见。
2。没有同步的问题
- 如果没有同步,其他线程可能看不到更改。
- 示例:停止带有布尔字段的线程(不同步)
public class stopthread {
private static boolean stoprequested = false;
public static void main(string[] args) throws interruptedexception {
thread backgroundthread = new thread(() -> {
while (!stoprequested) {
// loop infinito, pois mudanças em stoprequested podem não ser visíveis
}
});
backgroundthread.start();
thread.sleep(1000);
stoprequested = true; // pode nunca ser visto pela outra thread
}
}
3。通过同步修复
- 同步字段读写以确保可见性:
public class stopthread {
private static boolean stoprequested;
public static synchronized void requeststop() {
stoprequested = true;
}
public static synchronized boolean stoprequested() {
return stoprequested;
}
public static void main(string[] args) throws interruptedexception {
thread backgroundthread = new thread(() -> {
while (!stoprequested()) {
// loop agora termina corretamente
}
});
backgroundthread.start();
thread.sleep(1000);
requeststop();
}
}
4。使用 volatile 进行线程间通信
- 易失性修饰符保证可见性而无需互斥:
public class stopthread {
private static volatile boolean stoprequested = false;
public static void main(string[] args) throws interruptedexception {
thread backgroundthread = new thread(() -> {
while (!stoprequested) {
// loop agora termina corretamente com volatile
}
});
backgroundthread.start();
thread.sleep(1000);
stoprequested = true;
}
}
5。复合操作的问题(例如:非原子增量)
- 运算符不是线程安全的,因为它涉及多个操作:
public class serialnumbergenerator {
private static volatile int nextserialnumber = 0;
public static int generateserialnumber() {
return nextserialnumber++; // pode gerar números repetidos
}
}
同步修复:
public class serialnumbergenerator {
private static int nextserialnumber = 0;
public static synchronized int generateserialnumber() {
return nextserialnumber++;
}
}
- 使用 atomiclong 改进性能和安全性:
import java.util.concurrent.atomic.AtomicLong;
public class SerialNumberGenerator {
private static final AtomicLong nextSerialNumber = new AtomicLong();
public static long generateSerialNumber() {
return nextSerialNumber.getAndIncrement();
}
}
6。一般原则
避免共享可更改的数据:
- 尽可能首选不可变数据。
- 将可变数据限制在单个线程中。
安全发布:
确保共享对象对其他线程可见:
- 使用最终、易失性或显式同步字段。
- 使用并发集合,例如concurrenthashmap。
7。良好做法总结
- 始终同步共享可变数据的读写。
- 仅在线程之间进行简单通信时才使用 volatile。
- 优先选择线程安全的实用程序类,例如 java.util.concurrent. 包中的实用程序类
通过这些示例和实践,您可以创建清晰、正确且易于维护的并发程序。
书中的示例:














