How to run an application on multiple Threads?

Asked

Viewed 265 times

-1

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

Tela de cadastro

The user can register the amount of machines he wants, all this information is already being saved in the TXT file. According to my class Monitor:

public class Monitor extends javax.swing.JFrame {

private ArrayList<Computador> computadores;

  //    public ArrayList<Computador> getComputadores() {
  //        return computadores;
  //    }
   //
   //    public void setComputadores(ArrayList<Computador> computadores) {
  //        this.computadores = computadores;
  //    }
/**
 * Creates new form NovoJFrame
 */
public Monitor() {
    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();
                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);
        }
    });
}


}

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

Now that’s where my problem is, when I click the button GENERATE, the app is to get all the Ips that are on ArrayList and play on the thread, however it does not enter the loop that will do this. I put a test out of the loop and it performs only this test.

Below is the class responsible for taking the array information 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, (for now I have not played the information on the interface).

Saída

Every IP he picks up from ArrayList, it will run a computer in a thread and display on the interface the computer icon, the name of that machine, as well as its IP and its status.

Can anyone help me with developing this application?

  • Your question has more thread-related, no need for the object-oriented tag.

  • OK good Diego. Yeah, my problem that I can’t get the information of txt and play in arraylist, then play in Trhead

  • There are a lot of problems with your code. But since it’s incomplete (and the way you posted it, it doesn’t compile), it’s hard to handle all of them. Please post the complete code of the classes Monitor and Computador (including the imports and the initComponents()) that I tidy everything up and put a very legal answer.

  • Victor here is the link where all my project > https://www.dropbox.com/sh/5pzlui4lo17fvx6/ADqFltb1rr1rgTOzQQQDdMMMfa?dl=0

  • the project is compiling, but does not execute the Inetaddress function inside the thread

1 answer

2


Now that’s where my problem is, when I click the GENERATE button, the application is to take all the Ips that are in Arraylist and play on thread, but it does not enter the loop that will do this

So, you’ll never get in because you’re building the Intersection right before you get into 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 on the list of computers that is Monitor class attribute. To do 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 builder to power 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 iterate on 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’ve helped ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.