我想使用Java中的线程来制作一个简单的银行。 但我不能同步地进行存款(deposit())和取款(withdraw())操作。 余额一直没有同步。我在方法名前加上了“synchronized”关键字,但它从未起作用。 此外,我在我的ArrayList中使用了“synchronizedList”(我应该使用ArrayList来实现),但它也从未起作用。 如何获得适当的余额?请帮帮我。
import java.security.SecureRandom;
public class Transaction implements Runnable {
private static final SecureRandom generator = new SecureRandom();
private final int sleepTime; // random sleep time for thread
private String transaction;
private int amount;
private static int balance;
private Account account = new Account();
public Transaction (String transaction, int amount) {
this.transaction = transaction;
this.amount = amount;
sleepTime = generator.nextInt(2000);
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
if(transaction == "deposit") {
balance = account.deposit(amount);
} else if (transaction == "withdraw") {
balance = account.withdraw(amount);
}
System.out.println("[" + transaction + "] amount : " + amount +" balance : " + balance);
Thread.sleep(sleepTime);
}catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt(); // re-interrupt the thread
}
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AccountTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
// create ArrayList
List<Transaction> john = Collections.synchronizedList(new ArrayList<>());
// add Transaction objects
john.add(new Transaction("deposit", 1000));
john.add(new Transaction("withdraw", 500));
john.add(new Transaction("withdraw", 200));
john.add(new Transaction("deposit", 3000));
// execute Thread Pool
ExecutorService executorService = Executors.newCachedThreadPool();
// start transactions
for(int i=0; i<john.size(); i++) {
executorService.execute(john.get(i));
}
// shut down Thread Pool
}
}
public class Account {
// deposit withdraw
private static int balance;
public synchronized int deposit(int amount) {
balance += amount;
return balance;
}
public synchronized int withdraw(int amount) {
balance -= amount;
return balance;
}
}