有人可以判断下面的代码是否可以正常工作?
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();
}
答案 0 :(得分:2)
不,这段代码甚至都不会编译。例如,你的“UseFrequency”类有一个构造函数和一个run()方法,但是你有两行CriticalSection.freq[iFrequency] = true;
和
stop();
不在任何方法体中 - 他们只是独自坐在那里。
如果你得到编译它的代码仍然不会像你期望的那样工作,因为你有多个线程,没有并发控制。这意味着不同的线程可以“踩到彼此”并破坏共享数据,例如“freq”数组。只要有多个线程,就需要使用synchronized块来保护对共享变量的访问。并发Java教程在此解释了这一点http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
答案 1 :(得分:0)
您是否尝试过编译和测试?您使用的是Eclipse之类的IDE吗?您可以在调试器中单步调试程序,看看它在做什么。你的问题的结构方式,如果你的程序做了正确或错误的事情,没有人可以说出任何一种方式,因为在代码的注释中没有指定,也没有在提出的问题中指定。