この質問は、この質問のフォローアップです。同様の質問ですが、実行は異なります。以下のコードのように、オブジェクトをロックしていません。ですから、はっきりと理解しようとすると、私は正しいかどうかです。
本や記事を読んでこれまでにわかったこと:-
各スレッドは に入り、に応じてrun method
を取得し、どちらが正しい必要がありますか? そして、同期する必要のない別の方法がありますよね?id from the various pool (existPool or newPool)
if, else if block
attributeMethod
synchronized
attributeMethod
2 番目のスレッドも同時に起動するとしたら、以下の例で問題が発生するでしょうか?
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() {
}