Java多线程并发执行问题实例
在Java多线程并发执行中,常见的问题实例包括:
- 数据竞争:多个线程同时访问和修改共享的数据,可能会导致结果不一致。
// 示例:两个线程同时修改count
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
- 死锁:当两个或更多线程因争夺资源而造成的一种互相等待的现象被称为死锁。
// 示例:死锁产生
public class Banker {
private Account[] accounts;
public Banker(int numAccounts) {
accounts = new Account[numAccounts];
}
public synchronized void deposit(Account account, double amount) {
if (account.balance + amount > 0 && !contains(account)) {
account.balance += amount;
} else {
System.out.println("Insufficient funds or duplicate account.");
}
}
public synchronized void withdraw(Account account, double amount) {
if (amount <= account.balance) {
if (!contains(account)) {
account.balance -= amount;
} else {
System.out.println("Duplicate account. Unable to withdraw.");
}
} else {
System.out.println("Insufficient funds for withdrawal.");
}
}
private boolean contains(Account account) {
for (Account other : accounts) {
if (other == account || other.balance == account.balance) {
return true;
}
}
return false;
}
}
- 线程饥饿:当某些线程没有足够的资源(如CPU时间)来执行时,就会出现这种现象。
// 示例:线程饥饿问题
public class StarvationExample {
private int[] resources = new int[10];
public synchronized void acquireResource() {
while (resources[0] < 1) { // 线程饿死在这里
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
resources[0]--;
notifyAll(); // 通知所有等待的线程资源已释放
}
}
以上这些例子都是Java多线程并发执行中可能出现的问题。在实际编程时,需要充分理解并采取适当措施来避免这些问题。
还没有评论,来说两句吧...