Java多线程问题:死锁现象实例
死锁是一种在多线程环境下可能出现的严重问题。当两个或更多线程因争夺资源而造成的一种互相等待的现象时,就可能导致死锁。
下面是一个简单的Java多线程死锁实例:
// 定义一个共享资源,比如银行账户
class BankAccount {
private int balance = 0;
// 获取账户余额
public int getBalance() {
return balance;
}
// 存款
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
// 取款
public void withdraw(int amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}
}
// 创建两个线程,每个线程都有一个银行账户
public class DeadLockExample {
private BankAccount account1 = new BankAccount();
private BankAccount account2 = new BankAccount();
// 线程1:存款后取款
public void thread1() {
account1.deposit(50); // 存款
account1.withdraw(30); // 取款
System.out.println("Thread 1 completed");
}
// 线程2:取款后存款
public void thread2() {
account2.withdraw(40); // 取款
account2.deposit(60); // 存款
System.out.println("Thread 2 completed");
}
public static void main(String[] args) {
DeadLockExample example = new DeadLockExample();
Thread thread1 = new Thread(example::thread1));
Thread thread2 = new Thread(example::thread2));
thread1.start(); // 开始线程1
thread2.start(); // 开始线程2
try {
thread1.join(); // 等待线程1完成
thread2.join(); // 等待线程2完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个例子中,线程1先存款50,然后取款30。在这期间,线程2尝试从账户2取款40。
由于账户2的余额不足以支持这两次操作(取款后必须有足够余额进行存款),所以线程2会一直等待,形成死锁现象。
还没有评论,来说两句吧...