Java多线程并发问题:死锁案例

原创 以你之姓@ 2024-10-15 08:18 160阅读 0赞

死锁是多线程编程中的一种严重问题,它会导致所有线程都无法继续执行。

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

  1. // 线程1,拥有资源A和B
  2. class ResourceA {
  3. int count = 1;
  4. synchronized void use() {
  5. count--;
  6. System.out.println("Resource A used by Thread-1");
  7. if (count == 0) {
  8. System.out.println("Resource A released by Thread-1");
  9. }
  10. }
  11. }
  12. class ResourceB {
  13. int count = 1;
  14. synchronized void use() {
  15. count--;
  16. System.out.println("Resource B used by Thread-1");
  17. if (count == 0) {
  18. System.out.println("Resource B released by Thread-1");
  19. }
  20. }
  21. }
  22. // 线程2,拥有资源C和D
  23. class ResourceC {
  24. int count = 1;
  25. synchronized void use() {
  26. count--;
  27. System.out.println("Resource C used by Thread-2");
  28. if (count == 0) {
  29. System.out.println("Resource C released by Thread-2");
  30. }
  31. }
  32. }
  33. class ResourceD {
  34. int count = 1;
  35. synchronized void use() {
  36. count--;
  37. System.out.println("Resource D used by Thread-2");
  38. if (count == 0) {
  39. System.out.println("Resource D released by Thread-2");
  40. }
  41. }
  42. }
  43. public class DeadlockExample {
  44. private ResourceA ra1 = new ResourceA();
  45. private ResourceB rb1 = new ResourceB();
  46. private ResourceC rc1 = new ResourceC();
  47. private ResourceD rd1 = new ResourceD();
  48. public void startThreads() {
  49. // 线程1,获取资源A和B
  50. Thread thread1 = new Thread(() -> ra1.use() && rb1.use()));
  51. thread1.start();
  52. // 线程2,获取资源C和D
  53. Thread thread2 = new Thread(() -> rc1.use() && rd1.use()));
  54. thread2.start();
  55. }
  56. public static void main(String[] args) {
  57. DeadlockExample example = new DeadlockExample();
  58. example.startThreads();
  59. }
  60. }

这个例子中,线程1拥有资源A和B(ra1.use()rb1.use()),线程2拥有资源C和D(rc1.use()rd1.use())。

当线程1先使用完A后,会释放资源A,然后尝试去获取资源B。此时,如果线程2已经使用完C后释放了资源C,但是资源D还没被线程2使用完毕,那么线程1就无法获取到资源B,从而形成死锁。

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

发表评论

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

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

相关阅读