Java在线程的try-catch停止

时间:2017-11-10 05:50:59

标签: java try-catch throw continue java-threads

我正在尝试编写一个代码,当它与我的计算机在同一网络上时,它将返回我的覆盆子IP。这个想法是让它像Samba一样进行广播(广播解析是最接近原始NetBIOS机制的。基本上,寻找名为Trillian的服务的客户会喊出“哟!Trillian!你在哪里?”,等待具有该名称的机器用IP地址回答。来源:Samba团队)

所以这是代码:

public class GetIP {
    static String url; //global so I can access it after the threads are finished

    public class CheckIP extends Thread {
       private String url_test;

        public CheckIP(String url_t) {
            url_test = url_t;
        }

        public void run(){
            try {
                result = getHTML(this.url_test);  //result = the response from the GET request to this.url_test
            } catch (Exception e) {

            }

            if(result <is what I want>) {
                url = this.url_test  
                System.out.println("Flag 1");
                <I'd like to do something here, preferebly kill all other 
                threads that are trying to connect to an 'unserved' URL>
            }
        }
    }


    public static void main(String[] args) throws Exception{

        String ip_partial = <my computer's IP without the last part - ex: "192.168.0." , I'll hide the functions to make it short>;

        Thread myThreads[] = new Thread[254];
        for (int i = 1; i < 255; i++) {
            String url_test="http://"+ip_partial+i+":<port + endpoint>";
            GetIP getip = new GetIP ();
            myThreads[i] = new Thread(getip.new CheckIP(url_test));
            myThreads[i].start();
        }
        for (int i = 1; i < 254; i++) {
            System.out.println("Flag 2");
            myThreads[i].join(); //todo add catch exception
        }
    }   
}

我可以看到标志1,我确实打印了第一个'for'所以我知道有254个线程正在创建,但是我看不到标志2.它永远不会显示,无论我等多久。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您的代码存在问题java.lang.ArrayIndexOutOfBoundsException:

您正在执行循环直到第254个索引,而您的数组大小本身是 254 ,这意味着自从java启动以来,索引存在 253 它从0开始索引。

第一个循环也应该与第二个循环运行相同的迭代次数。

for (int i = 1; i < 254; i++) {
                    /\
                    ||
                    ||
                    ||
      This should not be 255 else you'll get OutOfBounds Exception.
}