这个问题是对这个问题的跟进,类似的问题,但执行不同,在下面的代码中,我对对象没有任何锁定。所以试图清楚地理解,我是对的还是不对的。
到目前为止,我通过阅读书籍和文章所了解的内容:-
每个 Thread 都会进入run method
,并且会得到id from the various pool (existPool or newPool)
依赖if, else if block
,那么它会进入attributeMethod
哪个必须是synchronized
正确的?还有另一种attributeMethod
不需要同步的方法吗?
所以假设如果第二个线程也同时启动,那么我会对下面的示例有任何问题吗?
private static final class Task implements Runnable {
private BlockingQueue<Integer> existPool;
private BlockingQueue<Integer> newPool;
private int existId;
private int newId;
private Service service;
public Task(Service service, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
this.service = service;
this.existPool = pool1;
this.newPool = pool2;
}
public void run() {
if(service.getCriteria.equals("Previous")) {
existId = existPool.take();
attributeMethod(existId);
} else if(service.getCriteria.equals("New")) {
newId = newPool.take();
attributeMethod(newId);
}
}
}
// So I need to make this method synchronized or not? Currently I have made this synchronized
private synchronized void attributeMethod(int range) {
// And suppose If I am calling any other method here-
sampleMethod();
}
// What about this method, I don't thinkg so, it will be synchronized as well as it will be in the scope of previous synchronized method whoever is calling, Right? or not?
private void sampleMethod() {
}