Dúvida com threads

HecKel

The WORM
Boas!

Estou a fazer um trabalho para a faculdade e necessitados de usar algumas threads...

Basicamente o trabalho é algo como um IRC limitado...

Algures no trabalho necessitámos de criar uma thread para ir recebendo dados do servidor, só que precisamos de aceder a estes dados no programa principal, sugestões?

Aqui ficam as funções deste problema:

Código:
(...)
public class VChatClient implements ChatProcessor {
(...)
    public List<String> getChatNames() {
        List<String> list = new ArrayList<String>();
        // TODO Completar codigo
        ChatRooms cr = new ChatRooms();
        cr.doit();
        // ------
        System.out.println( "Obter lista de nomes");
        return cr.getChannels();
    }
(...)
    class ChatRooms implements Runnable {
        
        // sala - hora
        private Map<String, Long> chanmap;
        private long timeout = 5000;
        
        public void run() {
            try{
                MulticastSocket receiver = new MulticastSocket(9500);
                receiver.joinGroup(InetAddress.getByName("255.0.0.0"));
                for(;;) {
                    byte[] buf = new byte[1024];
                    DatagramPacket dp = new DatagramPacket(buf, buf.length);
                    receiver.receive(dp);
                    String channels = new String(dp.getData(), 0, dp.getLength());
                    String[] chanarray = channels.split(";");
                    chanmap = new HashMap<String, Long>();
                    for(int i = 0; i < channels.length(); i++)
                        chanmap.put(chanarray[i], System.nanoTime());
                }
            } catch (IOException e)
            {}
        }
        
        public void doit() {
            Thread t = new Thread(this) ;
            t.start();
        }
        
        public List<String> getChannels() {
            Iterator<Entry<String, Long>> it = chanmap.entrySet().iterator();
            List<String> list = new ArrayList<String>();
            
            while(it.hasNext()) {
                Entry<String, Long> ent = it.next();
                if((System.nanoTime() - ent.getValue()) > timeout)
                    chanmap.remove(ent.getKey());
                else
                    list.add(ent.getKey());
            }
            return list;
        }
    }
}
A classe ChatRooms é nested class.

Sugestões agradecem-se :P

abraços, HecKel

PS: É provavel que este bloco de código ainda tenha erros, nem foi testado, ignorem esses erros. Para já apenas quero saber como resolver isto das threads, sff.
 
Back
Topo