当前位置: 首页 > news >正文

Java并发编程,从线程安全到死锁避免的实战解析

Java并发编程是构建高性能系统的核心技能,但也伴随着复杂的挑战。本文通过实际代码示例,系统讲解线程安全、死锁、资源竞争等常见问题的解决方案,并深入探讨如何利用Java并发工具包(java.util.concurrent)构建健壮的并发程序。

一、线程安全问题与解决方案

1.1 共享资源的竞态条件(Race Condition)

问题现象
多个线程同时修改共享变量,导致数据不一致。

public class Counter {private int count = 0;public void increment() {count++; // 非原子操作}public int getCount() {return count;}
}// 测试代码
public class RaceConditionTest {public static void main(String[] args) throws InterruptedException {Counter counter = new Counter();Thread t1 = new Thread(() -> {for (int i = 0; i < 10000; i++) {counter.increment();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 10000; i++) {counter.increment();}});t1.start();t2.start();t1.join();t2.join();System.out.println("Expected: 20000, Actual: " + counter.getCount());}
}

输出结果

Expected: 20000, Actual: 18437

解决方案

使用synchronized关键字
public class SafeCounter {private int count = 0;public synchronized void increment() {count++;}public synchronized int getCount() {return count;}
}
使用ReentrantLock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class SafeCounter {private int count = 0;private Lock lock = new ReentrantLock();public void increment() {lock.lock();try {count++;} finally {lock.unlock();}}public int getCount() {lock.lock();try {return count;} finally {lock.unlock();}}
}
使用AtomicInteger
import java.util.concurrent.atomic.AtomicInteger;public class SafeCounter {private AtomicInteger count = new AtomicInteger(0);public void increment() {count.incrementAndGet(); // 原子操作}public int getCount() {return count.get();}
}

二、死锁问题与避免策略

2.1 死锁产生的条件

四个必要条件

  1. 互斥(Mutual Exclusion)
  2. 请求与保持(Hold and Wait)
  3. 不可抢占(No Preemption)

文章转载自:

http://aRzzHlMQ.cybch.cn
http://men97ITZ.cybch.cn
http://88Dodd7t.cybch.cn
http://QPUwMpAH.cybch.cn
http://PbKesMcv.cybch.cn
http://enYOJKhn.cybch.cn
http://kwecQr6E.cybch.cn
http://GfpEeyod.cybch.cn
http://FHxULxvw.cybch.cn
http://sukYD8bV.cybch.cn
http://amdE0cPz.cybch.cn
http://VGfn3yaP.cybch.cn
http://V8K3Qlg5.cybch.cn
http://Ti77rKPu.cybch.cn
http://2P2s9Brd.cybch.cn
http://nThCGbdX.cybch.cn
http://wsqp6ok6.cybch.cn
http://yGwCI5HB.cybch.cn
http://ZTD6t8xM.cybch.cn
http://xfEIX8xA.cybch.cn
http://A6VkXlS6.cybch.cn
http://XZHhvYaL.cybch.cn
http://xTemDDOV.cybch.cn
http://aYtzLrh6.cybch.cn
http://Prgw75JF.cybch.cn
http://LE5GoKXE.cybch.cn
http://RKYVtYdE.cybch.cn
http://9qpH5V59.cybch.cn
http://gHM0jJx6.cybch.cn
http://46ZVnqQw.cybch.cn
http://www.dtcms.com/a/182287.html

相关文章:

  • Ubuntu 安装 HAProxy
  • 基于ESP32控制的机器人摄像头车
  • spark-Join Key 的基数/rand函数
  • 海纳思(Hi3798MV300)机顶盒遇到海思摄像头
  • RT-Thread 深入系列 Part 5:物联网与网络应用实战
  • 51c视觉~合集37
  • 使用FastAPI微服务在AWS EKS上实现AI会话历史的管理
  • 计算机网络 4-2-2 网络层(IPv4)
  • 解锁 DevOps 新境界 :使用 Flux 进行 GitOps 现场演示 – 自动化您的 Kubernetes 部署
  • 【RT-Thread Studio】nor flash配置Fal分区
  • Windows:Powershell的使用
  • 程序代码篇---esp32视频流处理
  • Taro 编译不平不同平台小程序
  • 《类和对象(中)》
  • 分布式事务快速入门
  • Ubuntu 与 Windows 双系统环境下 NTFS 分区挂载教程
  • Autoware message_filters::Synchronizer链接错误问题
  • 如何删除网上下载的资源后面的文字
  • 数字孪生实战笔记(1)数字孪生的含义、应用及技术体系
  • zdir3个人网盘dockerfile打包
  • 深入解析:如何基于开源p-net快速开发Profinet从站服务
  • C# WinForm DataGridView 非常频繁地更新或重新绘制慢问题及解决
  • WPF 性能 UI 虚拟化 软件开发人员的思考
  • gvm安装go报错ERROR: Failed to use installed version
  • C++GO语言微服务之用户信息处理
  • 深圳SMT贴片加工厂制造流程解析
  • 4.分布式锁
  • Pale Moon:速度优化的Firefox定制浏览器
  • vue访问后端接口,实现用户注册
  • 【金仓数据库征文】_金仓数据库在金融行业的两地三中心容灾架构实践