Grab attributes from a Thread object?

Asked

Viewed 655 times

2

Is it possible to take the attributes of a Thread object? because I am using threads to read several files (one per thread) (which have float numbers separated by n) store the floats to sum the floats and average values, however it is necessary to make a general sum of the files but I cannot get the values generated inside the thread by the main class.

main class:

package multithread;

import java.util.ArrayList;
import java.util.List;

public class MultiThread {

public static void main(String[] args) {
    List<String> pathsCemMil = new ArrayList<String>();
    pathsCemMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatCemMil_A.txt");
    pathsCemMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatCemMil_B.txt");
    pathsCemMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatCemMil_C.txt");

    List<String> pathsDezMil = new ArrayList<String>();
    pathsDezMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatDezMil_A.txt");
    pathsDezMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatDezMil_B.txt");
    pathsDezMil.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatDezMil_C.txt");

    List<String> pathsUmMilhao = new ArrayList<String>();
    pathsUmMilhao.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatUmMilhao_A.txt");
    pathsUmMilhao.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatUmMilhao_B.txt");
    pathsUmMilhao.add("C:\\Users\\Ricardo\\Documents\\NetBeansProjects\\MultiThread\\src\\arquivos\\NumerosFloatUmMilhao_C.txt");

    List<Thread> threadsDezMil = new ArrayList<Thread>();
    for(String path : pathsDezMil){
        threadsDezMil.add(new Worker(path));

    }

    List<Thread> threadsCemMil = new ArrayList<Thread>();
    for(String path : pathsCemMil){
        new Worker(path).start();
    }

    List<Thread> threadsUmMilhao = new ArrayList<Thread>();
    for(String path : pathsUmMilhao){
        new Worker(path).start();
    }
}

}

Thread class:

package multithread;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Worker extends Thread{
String path;
double valoresSoma;
double valoresMedia;
int valoresAcimaMedia;

public Worker(String path){
    this.path = path;
}

public void run(){
    try {
        List<Double> valores = new ArrayList<Double>();
        valores = reader(this.path);
        valoresSoma = soma(valores);
        valoresMedia = media(valoresSoma,valores.size());
        valoresAcimaMedia = acimaMedia(valores, valoresMedia);
        System.out.println(this.path);
        System.out.println(valores.size());
        System.out.println(valoresSoma);
        System.out.println(valoresMedia);
        System.out.println(valoresAcimaMedia);
    } catch (IOException ex) {
        Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
    }
}
public static List<Double> reader(String path) throws IOException{
    List<Double> valores = new ArrayList<>();
    FileReader fileReader = new FileReader(path);
    BufferedReader reader = new BufferedReader(fileReader);
    String data = null;
    while((data = reader.readLine()) != null){
        valores.add(Double.parseDouble(data)); 
    }
    fileReader.close();
    reader.close();
    return valores;
}

public static double soma(List<Double> valores){
    double soma = 0;
    for(Double valor : valores){
        soma += valor;
    }
    return soma;
}

public static double media(double soma, int qtde){
    return soma/qtde;
}

public static int acimaMedia(List<Double> valores, double media){
    int qtde = 0;
    for(Double valor : valores){
        if(valor > media){
            qtde++;
        }
    }
    return qtde;
}
}

File example that has the float values:

898.29
653.46
572.77
669.53
695.89
400.91
392.73
547.55
748.77
38.43

1 answer

1


It is possible to recover information from objects normally, but you need to wait for the threads finalize the execution before attempting to do so.

If you want to do it by hand, use the basic Java sync commands wait and notify.

However, there is a much easier API to work with threads and synchronization, the ThreadPoolExecutor.

Look at the simple example I did:

Thread

public class Worker implements Runnable {

    int soma;

    public void run() {
        //executa operações complexas
        soma = new Random().nextInt();
    }

    public int getSoma() {
        return soma;
    }

}

Code manager

//cria pool de threads para execução de tarefas
ThreadPoolExecutor p = new ThreadPoolExecutor(5, 10, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10));

//cria threads com tarefas a executar
Worker w1 = new Worker(); 
Worker w2 = new Worker(); 
Worker w3 = new Worker();

//submete tarefas para a execução
p.submit(w1);
p.submit(w2);
p.submit(w3);

//força a execução e finalização das threads
p.shutdown();

//aguarda finalização das threads em execução
p.awaitTermination(1, TimeUnit.DAYS);

//recupera resultados parciais e exibe
int soma = w1.getSoma() + w2.getSoma() + w3.getSoma();
System.out.println("Soma = " + soma);

Browser other questions tagged

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