-3

以下のコードが正常に機能するかどうかを誰かに教えてもらえますか?

class CriticalSection{

int iProcessId, iCounter=0;

public static boolean[] freq = new boolean[Global.iParameter[2]];

int busy;

//constructors

CriticalSection(){}

CriticalSection(int iPid){
    this.iProcessId = iPid;
}

int freqAvailable(){

for(int i=0; i<
Global.iParameter[2]; i++){

        if(freq[i]==true){
            //this means that there is no frequency available and the request will be dropped
            iCounter++;
        }   
    }
    if(iCounter == freq.length)
        return 3;

    BaseStaInstance.iNumReq++;
    return enterCritical();
}

int enterCritical(){

    int busy=0;
    for(int i=0; i<Global.iParameter[2]; i++){
        if(freq[i]==true){
            freq[i] = false;
            break;
        }
    }
    //implement a thread that will execute the critical section simultaneously as the (contd down)
    //basestation leaves it critical section and then generates another request
    UseFrequency freqInUse = new UseFrequency;
    busy = freqInUse.start(i);

//returns control back to the main program

    return 1;   
}
}

class UseFrequency extends Thread {

    int iFrequency=0;

     UseFrequency(int i){
        this.iFrequency = i;
     }
     //this class just allows the frequency to be used in parallel as the other basestations carry on making requests
    public void run() {
        try {
            sleep(((int) (Math.random() * (Global.iParameter[5] - Global.iParameter[4] + 1) ) + Global.iParameter[4])*1000);
        } catch (InterruptedException e) { }
    }

    CriticalSection.freq[iFrequency] = true;

    stop();

}  
4

2 に答える 2

2

いいえ、このコードはコンパイルされません。たとえば、「UseFrequency」クラスにはコンストラクターと run() メソッドがありますが、2 つの行がCriticalSection.freq[iFrequency] = true;あり stop();、どのメソッド本体にもありません。それらは単独でそこにあるだけです。

コードをコンパイルしても、複数のスレッドがあり、同時実行制御がないため、期待どおりに動作しません。つまり、異なるスレッドが「互いに踏み込み」、「freq」配列などの共有データを破損する可能性があります。複数のスレッドがある場合は常に、同期ブロックで共有変数へのアクセスを保護する必要があります。同時実行に関する Java チュートリアルでは、これについて説明していますhttp://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

于 2010-03-02T19:07:29.003 に答える
0

コンパイルしてテストしてみましたか?Eclipseのような IDE を使用していますか? デバッガーでプログラムをステップ実行して、その動作を確認できます。コードのコメントにも提起された質問にも何も指定されていないため、あなたの質問がどのように構成されているかは、あなたのプログラムが正しいことをしているのか間違っているのかを誰にもわかりません。

于 2010-03-02T19:04:59.540 に答える