附加内容:
线程间的同步与通信
问题: 线程在访问共享数据时可能会互相干扰。
解决方案:
同步方法
synchronized void synchronizedmethod() {
// código sincronizado
}
同步块:
synchronized (this) {
// código sincronizado
}
沟通示例:
线程之间使用wait()、notify()和notifyall()进行通信:
class SharedResource {
private boolean flag = false;
synchronized void produce() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Producing...");
flag = true;
notify();
}
synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consuming...");
flag = false;
notify();
}
}
public class ThreadCommunication {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(resource::produce);
Thread consumer = new Thread(resource::consume);
producer.start();
consumer.start();
}
}
结论

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