简体   繁体   中英

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".

I think it would be easier to understand if you had separate classes for Mine and Dwarf . If you had an extractDiamonds method on the Mine you could put synchronized on that method and achieve what you want. This is assuming you would create a single Mine object instance and somehow pass it to each Dwarf instance you create... or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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