Java多线程同步问题:死锁案例

原创 妖狐艹你老母 2024-10-08 02:03 176阅读 0赞

死锁是多线程编程中的一种严重问题。当两个或更多的线程在执行过程中,因争夺资源而造成的一种互相等待的现象称为死锁。

下面是一个简单的死锁案例:

  1. // 定义两个共享资源
  2. class Resource {
  3. private int count = 0;
  4. // 让一个线程增加count,另一个线程减少count
  5. public synchronized void increse() { count++; }
  6. public synchronized void decrease() { count--; if(count < 0) throw new RuntimeException("Invalid state"); }
  7. // 获取当前的count值,需要同步
  8. public synchronized int getCount() { return count; }
  9. }
  10. // 定义两个线程,每个线程都需要资源
  11. class WorkerThread implements Runnable {
  12. private Resource resource;
  13. public WorkerThread(Resource resource) { this.resource = resource; }
  14. @Override
  15. public void run() {
  16. try {
  17. // 线程A:增加count
  18. while (true) {
  19. if (resource.increase()) {
  20. System.out.println("Thread A increased count to " + resource.getCount());
  21. break;
  22. } else {
  23. System.out.println("Thread A couldn't increase count");
  24. Thread.sleep(1000);
  25. }
  26. }
  27. // 线程B:减少count
  28. while (true) {
  29. if (resource.decrease()) {
  30. System.out.println("Thread B decreased count to " + resource.getCount());
  31. break;
  32. } else {
  33. System.out.println("Thread B couldn't decrease count");
  34. Thread.sleep(1000);
  35. }
  36. }
  37. } catch (Exception e) {
  38. System.err.println(e.getMessage());
  39. }
  40. }
  41. }
  42. // 主程序,启动两个线程
  43. public class Main {
  44. public static void main(String[] args) {
  45. Resource resource = new Resource();
  46. Thread threadA = new Thread(new WorkerThread(resource)));
  47. Thread threadB = new Thread(new WorkerThread(resource)));
  48. // 启动线程
  49. threadA.start();
  50. threadB.start();
  51. // 等待所有线程完成
  52. try {
  53. threadA.join();
  54. threadB.join();
  55. } catch (InterruptedException e) {
  56. System.err.println(e.getMessage());
  57. }
  58. }
  59. }

在这个案例中,线程A需要增加资源的count值,而线程B需要减少这个count值。但由于两个线程同时操作同一个资源,可能导致循环等待(死锁)的情况。

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

发表评论

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

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

相关阅读

    相关 Java线同步问题——案例

    在Java多线程编程中,死锁是一种常见的并发问题。下面是一个简单的死锁案例: 假设我们有两个线程A和B,它们都需要两个资源:资源1(由线程B持有)和资源2(由线程A持有)。

    相关 Java线同步问题案例

    死锁是多线程编程中的一种严重问题,当两个或更多的线程在执行过程中因争夺资源而造成的一种互相等待的现象叫做死锁。 下面是一个经典的死锁案例: 场景:有两个部门A和B,每个部门