为什么线程仍然不一致? [英] Why is threading is still inconsistent?

查看:117
本文介绍了为什么线程仍然不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些模拟银行转账的java代码。帐户类只有一个余额字段和一个向余额字段添加一些余额的转移方法。

I have a some java code that simulates bank transfers. The account class simply has a balance field and a transfer method that add some balance to the balance field.

TransferManager定义一个Transfer类,它接受两个Account对象来传输一个从一个帐户到另一个帐户的给定金额作为参数传递。

The TransferManager defines a Transfer class which takes two Account objects to transfer a given amount from the one account to the other that are passed as parameters.

管理器本身有两个需要同步的重要方法,因为它们都在同一个资源上运行它们将以线程方式调用:

The Manager itself has two important methods that need to be synchronized because the both operate on the same resource and they will be called in a threaded way:

public synchronized void issueTransfer(Account from, Account to, int amount) {
    openTransfers.add(new Transfer(from, to, amount));
    issuedTransfers++;
}

public synchronized void performTransfers() {
    for(Transfer transaction : openTransfers) {
        transaction.performTransfer();
            performedTransfers++;
    }       
    openTransfers.clear();
}

如果没有同步语句,我会在存储传输的arraylist上获得NullPointerExceptions,读取。

Without the synchronization statement here I get NullPointerExceptions on the arraylist where Transfers are stored and read.

BankTest产生10个线程,每个线程发出10次传输。看看BankTest.java吧。问题是并不总是发出10 * 10次转账。有时候有98或99:

BankTest spawns 10 threads, each issues 10 transfers. Just have a look at BankTest.java. The problem is that not always 10*10 transfers are issued. Sometimes there are 98 or 99:

我是否必须向BankTest.java添加同步?我该怎么办?还有其他想法或建议吗?

Do I have to add synchronization to BankTest.java? What should I do? Any other ideas or suggestions?

TransferManager.java http://pastebin.com/Je4ExhUz

BankTest.java http://pastebin.com/cdpWhHPb

Exersice3.java http://pastebin.com/v7pwJ5T1

Account.java http://pastebin.com/QYEeWy5Z

推荐答案

try {
    Thread.sleep(60);
} catch (InterruptedException e) {
    e.printStackTrace();
}

这并不保证所有线程都已完成

this does not guarantee that all threads are finished

而是将所有线程保留在列表中并在所有线程上调用join

instead keep all threads in a list and call join on all of them

try {
    for(Thread thr:threads)thr.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

这篇关于为什么线程仍然不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆