AnonymousAlias
AnonymousAlias

Reputation: 1399

Not entering thread method

i am writing code from online to create a chat application. After trouble shooting my program to find out why it is not working I have discovered that the code inside my run method here is not being reached. here is the snippet of code

public void listen()
{
    listen = new Thread("Listen") {
        public void run()
        {
            writeMessage("Working in here");
            while (true) {
                String message = client.receive();
                if (message.startsWith("/c/")) {
                    client.setID(Integer.parseInt(message.substring(3, message.length())));
                    writeMessage("Successfully connected to server" + client.getID());
                }
            }
        }
    };
}

It is reaching the listen method itself, because if i use the write message command before i declare the thread, it prints out the message for me, any idea from looking at this why it will not enter any further?

Thanks

Upvotes: 1

Views: 270

Answers (2)

Michael Gantman
Michael Gantman

Reputation: 7790

Certainly working with appropriate Execotor or even better ExecutorService is more appropriate way of working with threads today. Read about it here. But if you insist on working the old way then you need to invoke start() method of your thread. Methods start() and run() do the same thing, only run() execute your thread sequentially i.e. in the same thread where you invoked it and start() actually starts a new thread where your code is executed which is what you wanted in the first place

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120644

Calling start() on your Thread would do it:

public void listen()
{
    listen = new Thread("Listen") {
        public void run()
        {
            writeMessage("Working in here");
            while (true) {
                String message = client.receive();
                if (message.startsWith("/c/")) {
                    client.setID(Integer.parseInt(message.substring(3, message.length())));
                    writeMessage("Successfully connected to server" + client.getID());
                }
            }
        }
    };
    listen.start(); // <-- Add this line
}

Also, you typically don't want to extend Thread (which you are doing here with an anonymous class). Usually you'll want to create a Runnable and pass that to Thread's constructor instead:

Runnable r = new Runnable() {
    @Override
    public void run()
    {
        // Do some work here
    }
};

Thread listen = new Thread(r, "Listen");
listen.start();

Or even better, use an Executor, there aren't many good reasons to create your own Thread objects.

Upvotes: 4

Related Questions