Java并发编程:线程同步与死锁实例

原创 本是古典 何须时尚 2024-09-06 01:42 142阅读 0赞

在Java并发编程中,线程同步和死锁是两个重要的概念。下面我们将通过实例来详细讲解。

  1. 线程同步

    • synchronized关键字:用于修饰方法或代码块,保证同一时间只有一个线程访问。
    1. // 示例1: 互斥资源
    2. class Counter {
    3. private int count = 0;
    4. synchronized void increment() {
    5. count++;
    6. notifyAll(); // 唤醒等待的线程
    7. }
    8. synchronized int decrement() {
    9. if (count > 0) {
    10. count--;
    11. notifyAll();
    12. return count;
    13. }
    14. throw new IllegalStateException("Counter underflow!");
    15. }
    16. }
    17. // 示例2: 同步代码块
    18. class BankAccount {
    19. private double balance = 0;
    20. void deposit(double amount) {
    21. synchronized (this) { // 同步整个类实例
    22. if (amount > 0) {
    23. balance += amount;
    24. notifyAll(); // 唤醒等待的线程
    25. return;
    26. }
    27. throw new IllegalArgumentException("Deposit amount cannot be negative!");
    28. }
    29. }
    30. void withdraw(double amount) {
    31. synchronized (this) { // 同步整个类实例
    32. if (amount > 0 && balance >= amount) {
    33. balance -= amount;
    34. notifyAll(); // 唤醒等待的线程
    35. return;
    36. }
    37. throw new IllegalArgumentException("Withdrawal amount exceeds current balance!");
    38. }
    39. }
    40. double getBalance() {
    41. synchronized (this) { // 同步整个类实例
    42. return balance;
    43. }
    44. }
  2. 死锁

    • 定义:两个或多个线程在执行过程中,因争夺资源而造成的一种相互等待的现象。
    1. // 示例: 死锁条件
    2. class DeadLock {
    3. private Object lock1 = new Lock1();
    4. private Object lock2 = new Lock2();
    5. void acquireLock1() throws InterruptedException {
    6. synchronized (lock1) { // 获取锁1
    7. acquireLock2(); // 获得锁2后返回
    8. return;
    9. }
    10. }
    11. void acquireLock2() throws InterruptedException {
    12. synchronized (lock2) { // 获取锁2
    13. acquireLock1(); // 获得锁1后返回
    14. return;
    15. }
    16. }
    17. }

通过以上实例,我们可以理解Java并发编程中的线程同步和死锁的概念。

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

发表评论

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

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

相关阅读