2
我使用Eclipse KEPLER [我愛Eclipse JUNO版本] 警告:我的英文不好,請糾正我或發現無意義的句子。可以一個java可執行文件同時運行多個循環
我的問題是: 我有一個程序在主循環內部有很多循環,我注意到一個嚴重故障,這將導致整個程序每3秒被卡住,然後再次喚醒。 [我想發送的代碼,但它包括超過14班,所以...也許我不會發送它]
該問題是由循環造成的,這需要很長時間才能完成。如果這些「循環」在「主循環」中,這個「主循環」需要3秒鐘才能再次啓動[這是不可接受的]
因爲代碼的堆積,我寫了一個我的問題的例子,它可能包含可能的解決方案,但我不知道如何做到這一點:
public class EX1 {
static public String w=""; // something where program can storage stuff
static public String alp="AaÁáÂâÄäÃãÅåÀàBbCcDdEeÉéÊêËëÈèFfGgHhIiÍíÎîÏïÌìJjKkLlMmNnÑñOoÓóÔôÖöÕõÒòPpQqRrSsTtUuÚúÛûÜüÙùVvWwXxYyÝýÿZz1234567890 ";
public static void StuffThatSupposeToBeAlwaysOn(){ // As I told here is loop that suppose to be running all time
int rand=0; // in this example, this loop works as random text generator
for(int a=0;a<100;a++){
rand=(int)(Math.random()*alp.length()-1);
w=w+(alp.substring(rand,rand+1));
}
}
public static void StuffThatSupposeToBeAlwaysOn2(){ //this suppose to be another same time running loop
/*
* printed String w should always be 16 letters long
* but because program run both loops one by one, it simply can't print it right length (16)
* so it print it as max length of loop (100)
*/
for(int a=0;a<50;a++){
if(w.length()>15){
System.out.println("Randomly generated text: "+w+". length of text is: "+w.length());
w="";
}
}
}
public static void main(String[] args) {// main program
long a=System.currentTimeMillis();
while(a+2000>System.currentTimeMillis()){ //Main loop[automated kill after 2 seconds]
StuffThatSupposeToBeAlwaysOn(); // so if I get both running at same time, problem is solved.
StuffThatSupposeToBeAlwaysOn2();
}System.exit(0);//program gets killed here
}
}
是的,萬一你多線程你的應用程序。 http://docs.oracle.com/javase/tutorial/essential/concurrency/ –
看起來你必須學習Runnable和Thread的工作方式。 – Julien