-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() 方法,但是你有两行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 回答