0

I'm trying to implement a program that starts two threads one of the threads loops forever to receive objects on a port and then add them to an array list which is shared between threads, the other thread loops forever to receive command to remove an object from the array list which is shared.

here is the code instantiating those threads

Host being the main class which contains two classes register and deregister (the threads)

static ArrayList<User> Clients=new ArrayList<User>();
Host.register reg=h.new register();
Thread t=new Thread(reg);
t.run();
Host.deregister dereg=h.new deregister();
Thread t1=new Thread(dereg);
t1.run();

and here are the threads themselves

public class register implements Runnable{
    private static final int PORT = 9111;
    @Override
    public void run() {
        listen();
    }
    public void listen(){
        try {
            ServerSocket s=new ServerSocket(PORT);
            while(true){
                Socket clsocket=s.accept();
                User recUser=null;
                ObjectInputStream in = new ObjectInputStream(clsocket.getInputStream());
                recUser=(User)in.readObject();
                Clients.add(recUser);
                in.close();
                clsocket.close();
                System.out.println(Clients.size()+" reg");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class deregister implements Runnable{
    private static final int PORT = 9999;
    @Override
    public void run() {
        listen();
    }
    public void listen(){
        try {
            ServerSocket s=new ServerSocket(PORT);
            while(true){
                Socket clsocket=s.accept();
                User recUser=null;
                ObjectInputStream in = new ObjectInputStream(clsocket.getInputStream());
                recUser=(User)in.readObject();
                Clients.remove(recUser);
                in.close();
                clsocket.close();
                System.out.println(Clients.size()+" dereg");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

My problem is that the only thread actually active and listening for objects is the first on instantiated, why are they not actually running in parallel and both listening at the same time?

Ali Elgazar
  • 777
  • 2
  • 12
  • 26
  • 1
    I don't think this will work as you expect. My understanding is that you can have multiple threads listening on the port but __only__ 1 will receive the datagram, making the whole thing moot. Have something listening on the port and spawn threads to handle the data instead. – rollingBalls Aug 30 '14 at 20:08

1 Answers1

8

You don't start a thread with run. You start it with start().

t.run() only runs the run() method on the current (main) thread, which is why t1.run() is not reached.

Change it to t.start() and t1.start().

Eran
  • 387,369
  • 54
  • 702
  • 768