【发布时间】:2020-11-25 18:49:23
【问题描述】:
我想用 Java 中的线程创建一个简单的银行。 但是我不能让 deposit(),withdraw() 同步。 始终没有同步平衡。我写的 方法名称中的“同步”关键字,但它永远不会起作用。 另外,我在我的 ArrayList 中制作了“synchronizedList”(我应该使用数组列表来制作它),但它永远不会起作用。我怎样才能获得适当的平衡?请帮帮我。
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;
}
}
【问题讨论】:
标签: java multithreading synchronized