[英]Can one java executable run more than one loop at the same time
我使用Eclipse KEPLER [我喜欢Eclipse JUNO版本]警告:我的英语根本不好,请纠正我,或者如果发现无意义的句子,请注意我。
我的问题是:我的一个程序的主循环中有很多循环,并且我注意到一个严重故障,这将导致整个程序每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
}
}
如果它们滞后于您的主循环,那么在这里多线程是个好用处,这样每个方法都可以在单独的线程上运行并在完成后反馈到主线程,而不会减慢主线程的运行速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.