线程允许无数活动同时发生。
并发编程比单线程编程更困难,因为很多事情都可能出错,而且故障很难重现。你无法避免竞争。它是平台固有的,也是从现在无处不在的多核处理器获得良好性能的要求。本章提供的建议可帮助您编写清晰、正确且文档齐全的并发程序。
1。共享可变数据同步的重要性
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++;
}
}
import java.util.concurrent.atomic.AtomicLong;
public class SerialNumberGenerator {
private static final AtomicLong nextSerialNumber = new AtomicLong();
public static long generateSerialNumber() {
return nextSerialNumber.getAndIncrement();
}
}
6。一般原则
避免共享可更改的数据:
安全发布:
确保共享对象对其他线程可见:
7。良好做法总结
通过这些示例和实践,您可以创建清晰、正确且易于维护的并发程序。
书中的示例:




以上就是Cap竞赛项目同步对共享可变数据的访问的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号