据我了解,下面的代码在synchronized
块中this
是一个计数器的实例。
问题一:在下面的例子中,这是否意味着当线程 A 到达synchronized
块时,线程 B 被阻止对 Counter 的实例做任何事情?换句话说,这是否意味着线程可以继续按他们看到的方式执行,但是在任何一个到达 synchronized
块时,另一个停止对类做任何事情,直到块退出?
public class Counter {
public void increment() {
// Some code
synchronized (this) { // <---- "this" is an instance of Counter
// Some more code
}
}
}
将上面的代码与
public class Counter {
List<String> listOfStrings = new ArrayList<String>();
public void increment() {
// Some code
synchronized (listOfStrings) {
// Some code that deals with
// listOfStrings
}
}
}
问题2:在上面的例子中,一旦线程A到达synchronized
块,线程B可以继续读写类中的任何东西,除了listOfStrings
ArrayList,它是块mutex
中的a。synchronized
它是否正确?
问题3:假设如果我们需要对多个对象进行修改是否更正确,this
我们mutex
应该使用?
例如:
public class Counter {
List<String> listOfStrings = new ArrayList<String>();
List<Integers> listOfIntegers = new ArrayList<Integers>();
public void increment() {
// Some code
synchronized (this) {
// Some code that deals with
// listOfStrings and listOfIntegers
}
}
}
我理解正确吗?如果我遗漏了什么,请更正。