Java并发问题:死锁案例分析

原创 淩亂°似流年 2024-09-26 01:00 147阅读 0赞

死锁是Java并发编程中一个常见的问题。它发生在两个或更多进程互相等待对方释放资源的情况,此时所有进程都无法继续。

以下是一个经典的死锁案例:

  1. // 进程A持有资源1,需要资源2
  2. class ProcessA implements Runnable {
  3. Resource1 r1;
  4. Resource2 r2;
  5. public ProcessA(Resource1 r1, Resource2 r2) {
  6. this.r1 = r1;
  7. this.r2 = r2;
  8. }
  9. @Override
  10. public void run() {
  11. // 执行需要资源2的代码
  12. while (r2.isAvailable()) {
  13. // 释放资源1,等待资源2
  14. r1.release();
  15. try {
  16. // 等待资源2可用
  17. Thread.sleep(50);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. // 执行需要资源1的代码
  23. while (r1.isAvailable()) {
  24. r1.acquire();
  25. try {
  26. Thread.sleep(50);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. }
  33. // 进程B持有资源2,需要资源1
  34. class ProcessB implements Runnable {
  35. Resource2 r2;
  36. Resource1 r1;
  37. public ProcessB(Resource2 r2, Resource1 r1) {
  38. this.r2 = r2;
  39. this.r1 = r1;
  40. }
  41. @Override
  42. public void run() {
  43. while (r1.isAvailable()) {
  44. r1.acquire();
  45. try {
  46. Thread.sleep(50);
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. // 执行需要资源2的代码,释放资源1
  51. r2.release();
  52. try {
  53. Thread.sleep(50);
  54. } catch (InterruptedException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. while (r2.isAvailable()) {
  59. r2.acquire();
  60. try {
  61. Thread.sleep(50);
  62. } catch (InterruptedException e) {
  63. e.printStackTrace();
  64. }
  65. // 执行需要资源1的代码,释放资源2
  66. r1.release();
  67. try {
  68. Thread.sleep(50);
  69. } catch (InterruptedException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. }

在这个例子中,ProcessA持有Resource1和需要Resource2,而ProcessB持有Resource2和需要Resource1

当两个进程都等待对方释放资源时(如ProcessA等待Resource2可用,ProcessB等待Resource1可用),就形成了死锁。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读