Java stops at try-catch thread

I am trying to write code that will return my raspberry IP address when it is on the same network as my computer. The idea is to make a broadcast such as Samba (broadcast resolution closest to the original NetBIOS engine. Basically, a client looking for a service called Trillian will call โ€œYo! Trillian! Where are you?โ€ And wait for the machine with this name to respond with an IP address.Source: Samba team)

So here is the code:

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 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 } } } 

I can see flag 1, and I printed the first "for", so I know that 254 threads have been created, but I can not see flag 2. It never shows, numerically, how long I wait. Any ideas why?

+5
source share
1 answer

The problem with your java.lang.ArrayIndexOutOfBoundsException: code java.lang.ArrayIndexOutOfBoundsException:

You loop to the 254th index , while the size of your array is 254 , which means that the index is 253 , since java starts it is indexed from 0.

The first loop should also run the same iterations as your second loop.

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

Source: https://habr.com/ru/post/1273254/


All Articles