[Resolvido]Thread and sockets

7 respostas
J

Amigos

este é um SW servidor que recebe conexões por socket, a cada novo cliente ele cria uma Thread.

import java.io.*;
import java.net.*;

class ClientWorker implements Runnable { // a classe implementa runnable
  private Socket client;
  int count = 0;
  ClientWorker(Socket client) {
   this.client = client;
   System.out.println("INICIANDO SOCKET SERVER");
    }

  public void run(){ //  segmento a ser exexutado
    String line;
    BufferedReader in = null;
    PrintWriter out = null;
    count ++;
    
    System.out.println(" Criado Thread : " + count);
    try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("in or out failed");
      System.exit(-1);
    }

    while(true){
      try{
        line = in.readLine();
//Send data back to client
        if(line.equals(">>CLIENT TERMINATE")){
        out.println("sessão terminada");
        System.out.println("sessão terminada");
       

        }
        if(line.equals("cliente1")){
         out.println("****" + line);
        }
         if(line.equals("cliente2")){
         out.println("#####" + line);
        }

          System.out.println(line);
              } catch (IOException e) {
         System.out.println("Read failed");
        
          //System.exit(-1);

    }
      
      }
      }
  }
//} //fim do metodo run

class SocketThrdServer { // classe interna

 
   ServerSocket server = null;
     SocketThrdServer(){ //Begin Constructor
 
   } //End Constructor

  public void listenSocket(){
    try{
      server = new ServerSocket(4444); 
    } catch (IOException e) {
      System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }
    while(true){
      ClientWorker w;
      try{
        w = new ClientWorker(server.accept()); // a cada solicitação de sockts
        Thread t = new Thread(w);                        // cria uma nova instancia de Client Worker
        t.start();
      } catch (IOException e) {
        System.out.println("Accept failed: 4444");
        System.exit(-1);
      }
    }
  }

    @Override
  protected void finalize(){
//Objects created in run method are finalized when 
//program terminates and thread exits
     try{
        server.close();
        System.out.println("socket fechado");
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
  }

  public static void main(String[] args){
        SocketThrdServer frame = new SocketThrdServer();
	
        frame.listenSocket();
  }
}

meu problema é que eu quero que quando ocorrer esta exceção(linhas 45,46) ele finalize a Thread onde a mesma ocorreu.

} catch (IOException e) {
         System.out.println("Read failed");

como fazer ??

sds

j.silvestre

7 Respostas

L

Coloca “break” no lugar do System.exit.

O jeito mais “certo” seria você ter uma variável boolean no lugar do seu while(true), e você atualiza ela para false quando você não quiser mais que fique no loop.

J

leo

entendi. a responsabilidade de terminar a Thread é minha. quando dou o break aThread automaticamente termina.
Agora eu pergunto porque o Thread.stop() se tornou maldito ?

e o destroy ??

public void destroy()

   // Destroys this thread, without any cleanup. Any monitors it has locked remain locked. (This method is not implemented.)

sds

j.silvestre

L

Oi,

Modifique:

while(true) {}

Por:

while (!Thread.currentThread().isInterrupted()) {}

Ou:

while (!this.isInterrupted() {} // this = referencia de sua thread.

Quando quiser mata-la, utilize o método interrupt() da própria thread.

Tchauzin!

L

Oi,

j.silvestre:
leo

entendi. a responsabilidade de terminar a Thread é minha. quando dou o break aThread automaticamente termina.
Agora eu pergunto porque o Thread.stop() se tornou maldito ?

Você já leu o javadoc?

"Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future. "

Em outras palavras, o stop() foi tornado deprecated porque:

"- Gera memory leaks;

  • Causa instabilidades no sistema;
  • Pode gerar catástrofes maiores."

Tchauzin!

V

Movido para o fórum de Java Avançado. Por favor, leia atentamente a descrição dos fóruns antes de postar.

L

O que acontece quando você dá “break”: o método run() sai do loop e termina. Quando o método run() termina, a Thread termina “junto”.

O jeito que eu e a lina respondemos é você não ter um loop infinito fazendo a leitura, mas sim fazendo algum tipo de controle externo (eu sugeri membro/variável booleana, lina sugeriu por interrupção da Thread).

O Thread.stop() se tornou “maldito” pelo mesmo motivo que desligar o computador no botão não é boa prática: o sistema (thread) é desligado sem ter nenhuma chance de salvar seu estado ou liberar recursos que estavam em uso. Isso pode causar o que lina disse: vazamento de memória (na verdade, memória que você perde acesso a ela e não pode ser desalocada porque você não tem acesso a ela (ficou confuso, e é confuso :lol: )), instabilidade por causa disso, e catástrofe maiores/imprevisíveis.

Pense assim: quando você vai desligar um carro, você gira a chave. E não simplesmente para o carro engatado e deixa morrer. Os dois métodos desligam o carro. Um é o “certo”, outro é o que causa mais danos.

J

Entendi…

acho que aquele avião da AirFrance que caiu no oceano devia estar com um Thread.stop(); hhehe…he…

valews…

sds

j.silvestre

Criado 31 de maio de 2011
Ultima resposta 1 de jun. de 2011
Respostas 7
Participantes 4