ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【JavaEE】线程安全性题目,线程不安满是怎么产生的,该如何应对 [打印本页]

作者: 宁睿    时间: 2024-11-21 20:55
标题: 【JavaEE】线程安全性题目,线程不安满是怎么产生的,该如何应对
产生线程不安全的原因

在Java多线程编程中,线程不安全通常是由于多个线程同时访问共享资源而引发的竞争条件。以下是一些导致线程不安全的常见原因:
产生线程不安全的案例以及应对方法

共享可变状态案例

我们将创建一个简单的银行账户类,多个线程并发访问该账户进行存款和取款操作。假设我们有两个线程同时对账户进行操作,可能会出现余额盘算错误的情况。
  1. class BankAccount {
  2.     private int balance = 100; // 初始余额为100
  3.     public void deposit(int amount) {
  4.         balance += amount; // 存款
  5.     }
  6.     public void withdraw(int amount) {
  7.         balance -= amount; // 取款
  8.     }
  9.     public int getBalance() {
  10.         return balance; // 返回当前余额
  11.     }
  12. }
  13. public class UnsafeBank {
  14.     public static void main(String[] args) {
  15.         BankAccount account = new BankAccount();
  16.         // 创建两个线程同时操作
  17.         Thread t1 = new Thread(() -> {
  18.             account.withdraw(50);
  19.             System.out.println("Thread 1 withdrew 50, balance: " + account.getBalance());
  20.         });
  21.         Thread t2 = new Thread(() -> {
  22.             account.deposit(30);
  23.             System.out.println("Thread 2 deposited 30, balance: " + account.getBalance());
  24.         });
  25.         t1.start();
  26.         t2.start();
  27.     }
  28. }
复制代码
运行情况:

我们盼望的运行结果是:取款50,余额50、存款30,余额80。但是上述结果并不是我们想要的
分析
在上述代码中,两个线程同时对balance变量进行操作,可能导致不一致的余额输出。比方,假设Thread 1先读取了余额为100,然后进行了取款操作,但在它更新余额之前,Thread 2可能已经读取了余额并进行了存款操作。最终的结果可能不符合预期。
解决方法

为相识决这个线程不安全的题目,我们可以利用synchronized关键字来确保对共享资源的访问是线程安全的。我们可以对deposit和withdraw方法加锁,使得同一时间只有一个线程能够执行此中一个方法。
以下是修改后的代码:
  1. class BankAccount {
  2.     private int balance = 100; // 初始余额为100
  3.     // 存款操作
  4.     public synchronized void deposit(int amount) {
  5.         balance += amount; // 存款
  6.     }
  7.     // 取款操作
  8.     public synchronized void withdraw(int amount) {
  9.         balance -= amount; // 取款
  10.     }
  11.     // 返回当前余额
  12.     public int getBalance() {
  13.         return balance; // 返回当前余额
  14.     }
  15. }
  16. public class SafeBank {
  17.     public static void main(String[] args) throws InterruptedException {
  18.         BankAccount account = new BankAccount();
  19.         // 创建两个线程同时操作
  20.         Thread t1 = new Thread(() -> {
  21.             account.withdraw(50);
  22.             System.out.println("Thread 1 withdrew 50, balance: " + account.getBalance());
  23.         });
  24.         Thread t2 = new Thread(() -> {
  25.             account.deposit(30);
  26.             System.out.println("Thread 2 deposited 30, balance: " + account.getBalance());
  27.         });
  28.         t1.start();
  29.         t2.start();
  30.         // 等待两个线程结束
  31.         t1.join();
  32.         t2.join();
  33.         
  34.         // 输出最终余额
  35.         System.out.println("Final balance: " + account.getBalance());
  36.     }
  37. }
复制代码
结果
在修改后的代码中,由于对deposit和withdraw方法加了synchronized修饰,确保任何时刻只有一个线程可以执行这两个方法,从而避免了由于竞争条件导致的不一致性。最终输出的余额将与预期结果相一致。

指令重排序案例

指令重排序是指在编译、优化或CPU执行过程中,代码的执行次序被改变。
count++操作并不是一个原子操作,它是由三个步骤构成的:
在多线程环境中,多个线程可能会同时对同一变量进行count++操作,导致结果不精确。这种情况下,指令重排序可能导致某些操作无法达到预期结果。
以下是一个示例代码,演示了这个题目:
  1. class Counter {
  2.     private int count = 0;
  3.     public void increment() {
  4.         count++; // 不安全的操作
  5.     }
  6.     public int getCount() {
  7.         return count;
  8.     }
  9. }
  10. public class CountExample {
  11.     public static void main(String[] args) throws InterruptedException {
  12.         Counter counter = new Counter();
  13.         
  14.         Thread[] threads = new Thread[10];
  15.         
  16.         // 创建10个线程
  17.         for (int i = 0; i < 10; i++) {
  18.             threads[i] = new Thread(() -> {
  19.                 for (int j = 0; j < 1000; j++) {
  20.                     counter.increment(); // 增加计数
  21.                 }
  22.             });
  23.         }
  24.         
  25.         // 启动所有线程
  26.         for (Thread thread : threads) {
  27.             thread.start();
  28.         }
  29.         // 等待所有线程结束
  30.         for (Thread thread : threads) {
  31.             thread.join();
  32.         }
  33.         // 输出最终计数
  34.         System.out.println("Final count: " + counter.getCount());
  35.     }
  36. }
复制代码
运行结果:

我们的预期结果是:10000
分析
在上述代码中,我们创建了10个线程,每个线程执行1000次increment()方法,从而盼望最终的计数是10000。然而,由于count++操作的非原子性,在多个线程并发执行时,可能会导致某些增量操作丢失,最闭幕果可能小于10000。
解决方法

为相识决这个题目,可以利用以下几种方法:
我们将采用第二种方法,即利用AtomicInteger来解决这个题目。
以下是修改后的代码:
  1. import java.util.concurrent.atomic.AtomicInteger;
  2. class Counter {
  3.     private AtomicInteger count = new AtomicInteger(0); // 使用AtomicInteger
  4.     public void increment() {
  5.         count.incrementAndGet(); // 原子性增加
  6.     }
  7.     public int getCount() {
  8.         return count.get(); // 获取当前值
  9.     }
  10. }
  11. public class SafeCountExample {
  12.     public static void main(String[] args) throws InterruptedException {
  13.         Counter counter = new Counter();
  14.         
  15.         Thread[] threads = new Thread[10];
  16.         
  17.         // 创建10个线程
  18.         for (int i = 0; i < 10; i++) {
  19.             threads[i] = new Thread(() -> {
  20.                 for (int j = 0; j < 1000; j++) {
  21.                     counter.increment(); // 增加计数
  22.                 }
  23.             });
  24.         }
  25.         
  26.         // 启动所有线程
  27.         for (Thread thread : threads) {
  28.             thread.start();
  29.         }
  30.         // 等待所有线程结束
  31.         for (Thread thread : threads) {
  32.             thread.join();
  33.         }
  34.         // 输出最终计数
  35.         System.out.println("Final count: " + counter.getCount());
  36.     }
  37. }
复制代码
不可见性案例

我们利用了两个线程t1和t2。线程t1负责不停地查抄一个共享变量fag,而线程t2则在休眠1秒后将fag设为1。
  1. public class Main {
  2.     public static int fag = 0;
  3.     public static void main(String[] args) throws InterruptedException {
  4.         Thread t1 = new Thread(() -> {
  5.             while (fag == 0) {
  6.             }
  7.         });
  8.         Thread t2 = new Thread(() -> {
  9.             try {
  10.                 Thread.sleep(1000);
  11.             } catch (InterruptedException e) {
  12.                 throw new RuntimeException(e);
  13.             }
  14.             fag = 1;
  15.         });
  16.         t1.start();
  17.         t2.start();
  18.         t1.join();
  19.         t2.join();
  20.         System.out.println("主线程结束");
  21.     }
  22. }
复制代码
分析
在Java中,fag是一个共享的静态变量,初始值为0。线程t1在一个循环中不断查抄fag的值,而线程t2在休眠1秒后将fag更新为1。根据Java内存模子的规定,线程可以在运行过程中缓存某些变量,以进步性能。这意味着,线程t1可能在本身的工作内存中读取到fag的值,而且不会每次都去主内存中查抄当其值变化时。
因此,虽然t2可能已经将fag设置为1,但如果t1线程没有看到这个变化,它仍然可能会在其循环中继续查看到fag为0,导致t1线程陷入死循环,程序执行不会继续下去。
解决方法

为相识决这个线程不可见性的题目,可以利用以下两种常见方法:
在这里,我们选择利用volatile关键字来解决这个题目。
  1. public class Main {
  2.     public static volatile int fag = 0; // 使用volatile关键字
  3.     public static void main(String[] args) throws InterruptedException {
  4.         Thread t1 = new Thread(() -> {
  5.             while (fag == 0) {
  6.                 // Busy wait: 这里循环等待fag变为1
  7.             }
  8.         });
  9.         Thread t2 = new Thread(() -> {
  10.             try {
  11.                 Thread.sleep(1000);
  12.             } catch (InterruptedException e) {
  13.                 throw new RuntimeException(e);
  14.             }
  15.             fag = 1; // 将fag设置为1
  16.         });
  17.         t1.start();
  18.         t2.start();
  19.         t1.join();
  20.         t2.join();
  21.         System.out.println("主线程结束");
  22.     }
  23. }
复制代码
结果
通过将fag声明为volatile,确保了对该变量的写入会使得线程t1线程能看到fag的最新值。即使线程t2在将fag改为1后,其他线程(如t1)也能及时看到这一变化,而不会出现不可见性的题目,从而避免了t1进入死循环的情况。
在程序运行结束后,您将看到"主线程结束"的输出,表明所有线程都能正常结束。利用volatile关键字有效地解决了线程间的可见性题目。
死锁

在多线程编程中,死锁是一种非常严重的题目,它会导致程序无法继续执行。产存亡锁的典范条件通常可以归纳为以下四个须要条件:
死锁案例

假设有两个线程,线程A和线程B,它们分别必要获取两个锁,锁1和锁2。以下是代码示例:
  1. class Lock {
  2.     private final String name;
  3.     public Lock(String name) {
  4.         this.name = name;
  5.     }
  6.     public String getName() {
  7.         return name;
  8.     }
  9. }
  10. public class DeadlockExample {
  11.     private static final Lock lock1 = new Lock("Lock1");
  12.     private static final Lock lock2 = new Lock("Lock2");
  13.     public static void main(String[] args) {
  14.         Thread threadA = new Thread(() -> {
  15.             synchronized (lock1) {
  16.                 System.out.println("Thread A: Holding lock 1...");
  17.                
  18.                 // Simulate some work
  19.                 try { Thread.sleep(100); } catch (InterruptedException e) {}
  20.                 System.out.println("Thread A: Waiting for lock 2...");
  21.                 synchronized (lock2) {
  22.                     System.out.println("Thread A: Acquired lock 2!");
  23.                 }
  24.             }
  25.         });
  26.         Thread threadB = new Thread(() -> {
  27.             synchronized (lock2) {
  28.                 System.out.println("Thread B: Holding lock 2...");
  29.                
  30.                 // Simulate some work
  31.                 try { Thread.sleep(100); } catch (InterruptedException e) {}
  32.                 System.out.println("Thread B: Waiting for lock 1...");
  33.                 synchronized (lock1) {
  34.                     System.out.println("Thread B: Acquired lock 1!");
  35.                 }
  36.             }
  37.         });
  38.         threadA.start();
  39.         threadB.start();
  40.     }
  41. }
复制代码
分析
在上面的代码中,线程A起首持有锁1,然后实验去获取锁2。同时,线程B起首持有锁2,之后实验获取锁1。这样就形成了循环等待,导致两个线程相互阻塞,从而发存亡锁。
解决方法

为了避免这种死锁情况,可以利用以下解决方案:
在这个示例中,无论线程A还是线程B,都会按照同样的次序(起首获取lock1,然后是lock2)来哀求锁,由此避免了死锁情况的发生。
通过这些方法,可以有效减少多线程程序中的死锁风险,保证程序的稳定性。
为了有效避免死锁,可以考虑以下计谋:

通过合理的设计与计划,可以有效减少死锁的可能性,进步体系的稳定性和可靠性。

博主介绍:大厂架构|《java全套学习资料》作者,阿里云开发社区乘风者计划专家博主,CSDN平台Java领域优质创作者,专注于大门生项目实战开发、讲解和结业答疑辅导。
   主要项目:小程序、SpringBoot、SSM、Vue、Html、Jsp、Nodejs等设计与开发。
  ??文末获取源码接洽??

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4