How to run an application in multiple threads?

-1

I'm developing an application with interface made by Swing. The purpose of the application is to simulate a computer network in which I will monitor using the InetAddress implementation. Well, I created my interface, where the user registers the machine name and its IP, as shown below:

Theusercanregisterasmanymachinesashewants,allthisinformationisalreadybeingsavedintheTXTfile.AspermyclassMonitor:

publicclassMonitorextendsjavax.swing.JFrame{privateArrayList<Computador>computadores;//publicArrayList<Computador>getComputadores(){//returncomputadores;//}////publicvoidsetComputadores(ArrayList<Computador>computadores){//this.computadores=computadores;//}/***CreatesnewformNovoJFrame*/publicMonitor(){initComponents();try{Scanners=newScanner(newFileInputStream("registro.txt"));
        while (s.hasNext()) {
            String var = s.nextLine();
            if (var.equals(" ")) {
                String nome = s.nextLine();
                String ip = s.nextLine();
                computadores.add(new Computador(nome, ip));
            }
        }
        s.close();
    } catch (FileNotFoundException e) {

    };
}


private void btnGravarMouseClicked(java.awt.event.MouseEvent evt) {                                       
    File arq = new File("registro.txt");
    btnGravar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Condição, verifica se os campo estão vazios.
            if (campoNome.getText().equals("")) {

                JOptionPane.showMessageDialog(null,
                        "Adicione um nome ao computador!");
                campoNome.requestFocus();
            } else if (campoIP.getText().equals("")) {
                JOptionPane.showMessageDialog(null,
                        "Adicione um IP!");
                // Fornece o foco ao cursor da caixa de Texto
                campoIP.requestFocus();
            } else {
                // Tratamento de Erros.
                try {
                    FileWriter fw = new FileWriter(arq, true);
                    try (BufferedWriter bw = new BufferedWriter(fw)) {
                        bw.write(campoNome.getText() + " ");
                        bw.write(campoIP.getText() + "\n");
                        bw.flush();
                        bw.close();
                    }
                    campoNome.setText("");
                    campoIP.setText("");
                    // Exibe caixa de Dialogo.
                    JOptionPane.showMessageDialog(null,
                            "Arquivo Gravado com Sucesso!");

                } catch (IOException Erro) {
                    JOptionPane.showMessageDialog(null,
                            "Erro ao Gravar no Arquivo" + Erro);
                }
            }
        }
    });

}                                      

private void btnAbrirMouseClicked(java.awt.event.MouseEvent evt) {                                      
    btnAbrir.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Computador cp = new Computador(null, null);
            cp.run();

        }
    });
}                                     

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Monitor().setVisible(true);
        }
    });
}


}

In this same class it opens the TXT file and saves the information in ArrayList<Computador> computadores;

Now that's where my problem when I click on the CREATE , the application is to get all of the IPs that are in the ArrayList and play in the thread, however it does not enter the loop who will do this. I put a test out of the loop and it only runs that test.

Below is the class responsible for picking up information from the array and playing in the thread:

Computer class

public class Computador extends javax.swing.JPanel implements Runnable {

private String nome;
private String ip;
//private boolean online;

private Thread processo;

/**
 * Creates new form Computador
 */
public Computador(String n, String i) {

    initComponents();

    nome = n;
    ip = i;
    //online = s;

    CampoNome.setText(n);
    CampoIP.setText(i);
    /*if(online) {
        CampoStatus.setText("Online");
    }else{
        CampoStatus.setText("Offline");
    }*/

    processo = new Thread(this);
    processo.start();
}

@Override
public void run() {

    while (true) {
        ArrayList<Computador> computadores = new ArrayList();

        for (int i = 0; i < computadores.size(); i++) {
            String addr = computadores.get(i).ip;

            try {
                if (InetAddress.getByName(addr).isReachable(3000)) {
                    String nome = InetAddress.getByName(addr).getHostName();
                    System.out.println("Host " + nome + " (" + addr + ") ativo!");
                } else {
                    System.out.println("Host " + addr + " inativo!");
                }
            } catch (UnknownHostException ex) {
                Logger.getLogger(Computador.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Computador.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        System.out.println("Testando");
        try {
            processo.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Computador.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Here is the output on the console, (so far I have not played the information in the interface).

For each IP that it gets from ArrayList , it will run a computer on a thread and display on the interface the computer icon, the name of that machine, as well as its IP and status.

Can anyone help me with the development of this application?

    
asked by anonymous 25.08.2016 / 15:15

1 answer

2
  

Now that's where my problem is, when I click the GENERATE button, the   application is to get all the IPs that are in the ArrayList and play in the   thread, but it does not enter the loop that will do this

So, it will never go in because you're building the collection just before you enter the loop:

ArrayList<Computador> computadores = new ArrayList(); //  Aqui tá sem itens!

    for (int i = 0; i < computadores.size(); i++) { // Size é 0 => (i < 0) = false

You need to iterate in the list of computers that is the attribute of the Monitor class. For this, I suggest you move this Computer ArrayList to a Controller class:

class ComputadorController {
     private static ArrayList<Computador> computadores = new ArrayList<Computador>();

     public static getComputadores() {
          return computadores;
     }
     public static setComputadores(ArrayList<Computador> computadores) {
          ComputadorController.computadores = computadores;
     }
}

Then just change the monitor constructor to feed this controller:

public Computador(String n, String i) {
    initComponents();

    try {
        Scanner s = new Scanner(new FileInputStream("registro.txt"));
        while (s.hasNext()) {
        String var = s.nextLine();
        if (var.equals(" ")) {
            String nome = s.nextLine();
            String ip = s.nextLine();
            ComputadorController.getComputadores().add(new Computador(nome, ip));
        }
    }
        s.close();
    } catch (FileNotFoundException e) {

    };
}

And in your loop you will begin to iterate in the list that was fed by the application:

@Override
public void run() {

while (true) {

    for (int i = 0; i < ComputadorController.getComputadores().size(); i++) {
         String addr = ComputadorController.getComputadores().get(i).ip;

My suggestion is the one that least alters the logic of your current implementation, but I suggest you refactor your code by looking at encapsulation, object orientation, name patterns, and exception handling.

I hope I have helped ^^

    
01.09.2016 / 14:16