簡體   English   中英

一個Java可執行文件可以同時運行多個循環嗎

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM