[英]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
实例( sneezy
, dopey
)都有自己的锁定/互斥/监视所以把synchronized
的run
方式不会同步任何每个方法正在与不同的“锁定”。
I think it would be easier to understand if you had separate classes for Mine
and Dwarf
. 如果您为Mine
和Dwarf
了单独的类,那么我认为它会更容易理解。 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.