Threads

2 respostas
T

Boa noite. Estou com dificuldades em realizar as comunicação de threads.

Tenho uma classe chamada controlador que é uma thread, e ela controla outras 3 threads.
Preciso dar um wait() nas threads secundárias e também preciso do notify(), sendo que na classe controlador existe um método chamado pararThreads() que deveria deixar3 em modo de espera com o wait, e um método reiniciarThreads() que executaria o notify().

alguém pode me dar um exemplo básico que como poderia fazer isso?

2 Respostas

Priuli

Vc poderia criar uma estrutura ± assim:

A primeira thread obtem\separa varios arquivos de uma pasta.
A segunda thread lê\processa as linhas dos arquivos
A terceira thread efetua uma chamada e/s (ftp, acesso a bd…) ou cria outro arquivo de resposta a partir do arquivo de entrada

o Controlador inicia as threads, reinicia, pausa, para todas ou algumas destas threads, é um trabalhinho!!

T

Vou postar oque eu fiz, não funcionou.
Alguém sabe porque não funcina?

package cd;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Controle extends Thread {

    Thread_ t1 = new Thread_("thread 1");
    Thread_ t2 = new Thread_("thread 2");
    Thread_ t3 = new Thread_("thread 3");
    Banco banco = new Banco();
    ArrayList<Lista> resultSet = new ArrayList<Lista>();
    private boolean statusAnterior = false;

    public void run() {
        this.carregarArraylist();
        this.iniciarThreads();
        while (true) {
            this.pausarThreads();
            this.reIniciarThreads();
        }
    }

    private void carregarArraylist() {
        banco.carregarArrayList(resultSet);
        statusAnterior = !resultSet.isEmpty();
    }

    private void pausarThreads() {
        try {
            t1.aguardar();
            t2.aguardar();
            t3.aguardar();
        } catch (Exception ex) {
            System.err.print(ex + " pausar Threads");
        }
    }

    private void reIniciarThreads() {
        System.out.println("Iniciou");
            t1.notify();
        synchronized (t1) {
            System.out.println("Iniciou");
            t1.notify();
        }
        synchronized (t2) {
            System.out.println("Iniciou");
            t1.notify();
        }
        synchronized (t3) {
            System.out.println("Iniciou");
            t1.notify();
        }
    }

    private void iniciarThreads() {
        try {
            t1.start();
            t2.start();
            t3.start();
            System.err.println("Threads iniciadas");
        } catch (Exception ex) {
            System.err.print(ex + " Reiniciar Threads");
        }
    }

    private void enviarRequisicao() {
    }

    private void dormir(int time) {
        try {
            sleep(time);
        } catch (Exception ex) {
            System.err.print(ex);
        }
    }

    private void verificarStatusLista() {
        if (!resultSet.isEmpty() != statusAnterior) {
            if (!resultSet.isEmpty()) {
                this.reIniciarThreads();
            } else {
                this.pausarThreads();
            }
        }
    }

    public void aguardar() {
        synchronized (t1) {
            try {
                System.out.println("t1  wait");
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread_.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        synchronized (t2) {
            try {
                System.out.println("t2  wait");
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread_.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        synchronized (t3) {
            try {
                System.out.println("t3  wait");
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread_.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
package cd;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Thread_ extends Thread {

    private String message = "";
     boolean x = true;
    public Thread_(String message) {
        this.message = message;
    }

    public void run() {
        while (true) {
            System.out.println(message);
        }
    }

    public void receberSolicitacao(Lista lista) {
    }

    public void aguardar() {
        synchronized (this) {
            try {
                System.out.println(message + "  wait");
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread_.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void dormir(int time) {
        try {
            sleep(time);
        } catch (Exception ex) {
            System.err.print(ex);
        }
    }
}
Criado 13 de abril de 2011
Ultima resposta 14 de abr. de 2011
Respostas 2
Participantes 2