0
I created a program that reads the information of some websites, stores this information in Arraylist’s each with its respective class.
In the GUI I put some options like search by name and date and so compared the fields typed or dates selected by the user with the information collected from the site, feeding a Jtable with this information, while one (by what I read) Worker Thread keeps updating wrong(creating another object of each class by pulling the site information and only at the end, exchanging the references of the class used as feed for Jtable)
Example:
MinhaClasse alimentadorDeJTable = new MinhaClasse();
MinhaClasse alimentadorDeJTablecache = new MinhaClasse();
alimentadorDeJTable = alimentadorDeJtablecache;
out that on another button called Terminal, when clicked, would use the Jtable powered to generate another Jtable with the difference of information dates of the site with the same name, but I can’t maintain concurrency(simultaneity) so that this is displayed in the correct way.
What I really need is help with Threads, in case you don’t want to read the codes because they are very long, I’m waiting for someone with more experience to give me a light on how Threads work, to direct to a slightly friendlier material with whom you’re getting started
Below follows one of the class that pulls information:
public class Porto implements GeradorDeTabela,Terminais
{
private ArrayList<String> nmNavio = new ArrayList<String>();
private ArrayList<String> nmTerminalE = new ArrayList<String>();
private ArrayList<String> nmAgente = new ArrayList<String>();
private ArrayList<String> dtChegada = new ArrayList<String>();
public Porto(WebDriver driver, boolean getInfoSite)
{
if(getInfoSite){
getSiteInfo(driver);
}
}
public void clone(Porto porto)
{
this.nmNavio.clear();
this.dtChegada.clear();
this.nmAgente.clear();
this.nmTerminalE.clear();
this.nmNavio.addAll(porto.getNmNavio());
this.dtChegada.addAll(porto.getDtChegada());
this.nmTerminalE.addAll(porto.getTerminalE());
this.nmAgente.addAll(porto.getNmAgente());
}
//Getters
public ArrayList<String> getNmNavio()
{
return nmNavio;
}
public ArrayList<String> getTerminalE()
{
return nmTerminalE;
}
public ArrayList<String> getNmAgente()
{
return nmAgente;
}
public ArrayList<String> getDtChegada()
{
return dtChegada;
}
//Métodos
public void getSiteInfo(WebDriver driver)
{
System.out.println("Conectando Porto");
nmNavio.clear();
dtChegada.clear();
try{Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
driver.get("http://www.portodesantos.com.br/esperados.php");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("navios")));
List<WebElement> lista = driver.findElements(By.tagName("tbody"));
for(int a = 0; a<lista.size();a++)
{
List<WebElement> listabody = lista.get(a).findElements(By.tagName("td"));
for(int b =0;b<listabody.size();b+=19)
{
nmNavio.add(listabody.get(b).getText());
dtChegada.add(listabody.get(b+4).getText().substring(0,10));
nmTerminalE.add(listabody.get(b+14).getText());
nmAgente.add(listabody.get(b+7).getText());
}
}System.out.println("Dados Coletados Porto");}catch(WebDriverException e)
{
driver.quit();
JOptionPane.showMessageDialog(null, "Falha ao carregar dados do Porto de Santos" , "Erro", JOptionPane.INFORMATION_MESSAGE);
throw new RuntimeException("Erro ao carregar Porto: "+e);
}
}
public DefaultTableModel geraTabela(JTable tbPesquisa)
{
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Navio","ETA","Terminal","Agente"});
for(int a = 0;a<nmNavio.size();a++)
{
for(int b=0;b<tbPesquisa.getRowCount();b++)
{
if(nmNavio.get(a).toString().toLowerCase().equals(tbPesquisa.getValueAt(b, 0).toString().toLowerCase().trim()))
model.addRow(new Object[]{nmNavio.get(a),dtChegada.get(a),nmTerminalE.get(a),nmAgente.get(a)});
}
}
return model;
}
public DefaultTableModel geraTabelaData(Date dataInicial, Date dataFinal)
{
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Navio","ETA","Terminal","Agente"});
for(int a = 0;a<dtChegada.size();a++)
{
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date today = formatter.parse(dtChegada.get(a));
System.out.println(today);
if( (today.before(dataInicial) && today.after(dataFinal)) || today.equals(dataInicial) || today.equals(dataFinal))
{
model.addRow(new Object[]{nmNavio.get(a),dtChegada.get(a),nmTerminalE.get(a),nmAgente.get(a)});
}
} catch (ParseException e) {
// TODO Auto-generated catch block
System.out.println("Alteraram o modo de exibição da data no site do Porto de santos");
e.printStackTrace();
}
}
return model;
}
}
This is the part of the GUI that uses Threads:
class Verifica implements Runnable
{
private volatile boolean flag = true;
@Override
public void run()
{
while(flag)
{
System.out.println("Entrei na Atualização");
getPorto().getSiteInfo(getDriver());
porto.clone(getPorto());
getPraticagem().getSiteInfo(getDriver());
praticagem.clone(getPraticagem());
btp.getSiteInfo(driver);
System.out.println("Dados da BTP ATUALIZADOS");
emb.getSiteInfo(driver);
System.out.println("Dados da Embraport ATUALIZADOS");
lbs.getSiteInfo(driver);
System.out.println("Dados da Libra ATUALIZADOS");
sbr.getSiteInfo(driver);
System.out.println("Dados da SantosBrasil ATUALIZADOS");
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void pause()
{
flag=false;
}
}
class VerificaTerminal implements Runnable
{
@Override
public void run()
{
ArrayList<Object[]> btpArray = btp.verificaTabela(tbPorto);
if(!btpArray.isEmpty())
{
listaDivergentecache.addAll(btpArray);
}
ArrayList<Object[]> embArray = emb.verificaTabela(tbPorto);
if(!embArray.isEmpty())
{
listaDivergentecache.addAll(embArray);
}
ArrayList<Object[]> lbsArray = lbs.verificaTabela(tbPorto);
if(!lbsArray.isEmpty())
{
listaDivergentecache.addAll(lbsArray);
}
ArrayList<Object[]> sbrArray = sbr.verificaTabela(tbPorto);
if(!sbrArray.isEmpty())
{
listaDivergentecache.addAll(sbrArray);
}
listaDivergente.clear();
listaDivergente.addAll(listaDivergentecache);
listaDivergentecache.clear();
}
}
Thread t2 = new Thread(new VerificaTerminal());
t2.start();
t1 = new Thread(new Verifica());
t1.start();
btnTerminais.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
if(!listaDivergente.isEmpty()){
System.out.println(listaDivergente);
TabelaTerminais panel = new TabelaTerminais();
panel.setTabelaTerminais(listaDivergente);
panel.setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Nenhuma informação divergente" , "InfoBox: " + "Lista Divergente", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
That answer can help you with the "I’m waiting for someone with more experience to shed some light on how Threads work".
– Renan Gomes
great reading, I understood perfectly how the threads work, how can I deepen? I would like material to start the studies in this part that I have difficulty, already read about semaforico, notify, notifyall,Ait, I know there are design Patterns and good practices, but I can not apply in my codes, because I could not fully understand the subject
– L. Simões