0

この質問は、この質問のフォローアップです。同様の質問ですが、実行は異なります。以下のコードのように、オブジェクトをロックしていません。ですから、はっきりと理解しようとすると、私は正しいかどうかです。

本や記事を読んでこれまでにわかったこと:-

各スレッドは に入り、に応じてrun methodを取得し、どちらが正しい必要がありますか? そして、同期する必要のない別の方法がありますよね?id from the various pool (existPool or newPool)if, else if blockattributeMethodsynchronizedattributeMethod

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() {


    }
4

1 に答える 1

1

2 番目のスレッドも同時に起動するとしたら、以下の例で問題が発生するでしょうか?

可能性として、そうするでしょう。前の質問に対する私の回答の 2 番目の箇条書きをもう一度読んでください。

基本的に、問題は、スレッドがそれぞれクラスの異なるインスタンスで同期Taskすることです...そして、それは相互排除を提供しません。

これが実際に問題になるかどうかは、スレッドを同期する必要があるかどうかによって異なります。この場合、スレッドは共有ServiceおよびBlockingQueueインスタンス化されるようです。それが共有の範囲であり、スレッドセーフな実装クラスを使用している場合、同期は必要ないかもしれません。


あなたへの私のアドバイスは、あなたのJavaの教科書/チュートリアルに戻って、何がsynchronizedプリミティブミューテックスが実際に何をするかについて彼らが言っていることを確認することです. それらは本当に非常に単純です...しかし、達成しようとしている目標を達成するためにそれらを正しく組み合わせる前に、プリミティブを完全に理解する必要があります。

于 2012-08-21T01:56:24.300 に答える