简体   繁体   English

并发编程问题Java

[英]Concurrent Programming issue java

So I am down to figuring out how to get the objects to keep track of how many diamonds they take with each iteration of the executor service 因此,我要弄清楚如何获取对象以跟踪执行程序服务的每次迭代所带走的钻石数量。

public class DwarfMine {

    public DwarfMine() {
    }

    public int diamonds = 100;

    public int getDiamonds() {
        return diamonds;
    }

    public synchronized int subtractDiamonds(int howMany) {
        diamonds -= howMany;
        System.out.println("There are now " + diamonds + " left in the mine!");
        return diamonds;
    }

}

Each DwarfMine instance ( sneezy , dopey ) has its own lock/mutex/monitor so putting synchronized on the run method doesn't synchronize anything as each method is working with a different "lock". 每个DwarfMine实例( sneezydopey )都有自己的锁定/互斥/监视所以把synchronizedrun方式不会同步任何每个方法正在与不同的“锁定”。

I think it would be easier to understand if you had separate classes for Mine and Dwarf . 如果您为MineDwarf了单独的类,那么我认为它会更容易理解。 If you had an extractDiamonds method on the Mine you could put synchronized on that method and achieve what you want. 如果您在Mine上有一个extractDiamonds方法,则可以extractDiamonds方法进行synchronized并实现所需的功能。 This is assuming you would create a single Mine object instance and somehow pass it to each Dwarf instance you create... or something similar. 这是假设您将创建一个Mine对象实例,并将其以某种方式传递给您创建的每个Dwarf实例……或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM