Asuu
Asuu

Reputation: 183

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;
    }

}

Upvotes: 1

Views: 80

Answers (1)

Drew MacInnis
Drew MacInnis

Reputation: 8587

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.

Upvotes: 2

Related Questions