There is a code to work with threads.
ExecutorService threads = java.util.concurrent.Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { // создаём поток threads.submit(new Runnable() { @Override public void run() { try { // какие-то инструкции потока } catch (Exception e) { } } }); }
The question is inside the stream:
- pinging
- connect to ssh server
- execution of several commands on it.
accordingly, this business takes some time, plus sometimes the server may not be available and the thread, respectively, runs longer than usual.
Required:
- run streams
- wait until all threads finish executing,
- continue with the main program.
Added by:
main ()
ExecutorService threads = java.util.concurrent.Executors.newCachedThreadPool(); Future<String>[] tasks = new Future[servers.size()]; for (int i = 0; i < servers.size(); i++) { tasks[i] = threads.submit(new Thread_server(servers.get(i))); } while(checkThreads(tasks)) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } threads.shutdown(); for (Future task : tasks) { try { System.out.println(task.get()); } catch (InterruptedException e) { } }
checkThreads function
private static boolean checkThreads(Future<String>[] tasks) { for (Future task : tasks) { if (!task.isDone()) { return true; } } return false; }
class Thread_server
public class Thread_server implements Callable { private Servers server = null; private String result = null; public Thread_server(Servers server) { this.server = server; } @Override public String call() { try { boolean ping = false; String host = null; if (server.getEnabled() == 1) { if (server.getVpnIp() != 0) { ping = true; host = new Libs().intToIp(server.getVpnIp()); } else { if (server.getGateIp()!= 0) { ping = true; host = new Libs().intToIp(server.getGateIp()); } } } if (ping) { InetAddress inet = InetAddress.getByName(host); boolean reachable = inet.isReachable(5000); if (reachable) { Ssh ssh = new Ssh(host); if (ssh.connect) { result = server.getName() + " - на связи (" + host + ") =>" + ssh.exec("uptime"); result = result + " Date:" + ssh.exec("date"); } else { result = server.getName() + " - НЕ на связи"; } ssh.sshDisconnect(); } else { result = server.getName() + " - НЕ на связи"; } } } catch (Exception e) { e.printStackTrace(); } finally { return result; } } }
The problem is that if in the 1st version all servers responded, then in the last version, the non-responders receive null, but should not.
Thread.start
andThread.join
. - VladDCallable<T>
, and not justRunnable
. Get on exitFuture<T>
. - VladD