2010-03-02 50 views
-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(); 

} 
+1

也許如果你正確地重新格式化/重新加載代碼。縮進是虛假的,這使得代碼很難解釋。如果您使用的是Eclipse,只需按下「Ctrl + Shift + F」即可。進一步詳細講述代碼的實際問題。怎麼了?不會發生什麼?它不夠嗎?我們可以複製'n'paste'n'run的SSCCE(http://sscce.org)會很棒。 – BalusC 2010-03-02 18:49:08

+0

而不是張貼一大塊代碼,你可能會考慮發佈有關代碼的更具體的問題與相關的片段。或者至少格式正確;沒有縮進就很難閱讀。 – 2010-03-02 18:49:32

+0

如果你不告訴我它打算做什麼,我該如何告訴你它是否會起作用?目前爲 – Pops 2010-03-02 18:49:57

回答

2

不,這段代碼甚至不會編譯。例如,你的「UseFrequency」類有一個構造函數和一個run()方法,但是你有兩行CriticalSection.freq[iFrequency] = true;stop();,它們不在任何方法體中 - 它們只是坐在那裏。

如果你得到編譯代碼,它仍然不會像你期望的那樣工作,因爲你有多個線程並且沒有併發控制。這意味着不同的線程可以「彼此相助」並破壞共享數據,比如你的「freq」數組。任何時候你有多個線程都需要用同步塊來保護對共享變量的訪問。關於併發性的Java教程在這裏解釋了這一點http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

+0

CriticalSection.freq [iFrequency] = true只是將CriticalSection類的布爾數組重新設置爲true。 ,我用stop()來終止當前線程。 但是,我明白你提到的有關同步塊的內容。下面的代碼會確保併發性嗎?我遺漏了大部分代碼,同步塊關注我。 (){ \t int busy = 0; (int i = 0; i 2010-03-02 19:30:57

+1

@ user282544:評論沒有格式,當你有這樣的改變時,你應該真的編輯你原來的帖子。但是,我會指出,stop()已被棄用,並且有充分的理由:http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html – Pops 2010-03-02 19:56:14

+0

非常感謝你的回覆。也感謝讓我注意到編輯我的原始帖子的代碼更改的想法,它不會發生在我身上 – 2010-03-02 20:24:12

0

你試過編譯和測試它嗎?你在使用像Eclipse這樣的IDE嗎?你可以在調試器中瀏覽你的程序,看看它在做什麼。你的問題的結構方式沒有人能夠以任何方式說明你的程序是正確的還是錯誤的,因爲沒有在代碼的註釋中指定,也沒有在提出的問題中指定。