-1

I did a little client server application in Java on LinuxOS, where the server receives different commands from the client and processes them by starting different threads. There is one specific thread for each command.

My main-program starts a thread, that responds to different commands and consists simplified of one infinite loop. There is no exit out of the loop yet. This Thread prints to the Terminal, where the main-program was started, but the commands after ".start()" aren't executed.

ServerSend servSend = new ServerSend(arg);
System.out.println("1"); 
servSend.start();
System.out.println("2");`

So "2" is never printed, whereas some "System.out.println()" inside the thread work. Does anybody have an idea why?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user1786193
  • 17
  • 1
  • 5

1 Answers1

1

If you are trying to spawn a new thread, I assume ServerSend implements java.lang.Runnable or extends java.lang.Thread in which case you should be overwriting the public void run() method, not the start() method.

ie:

public class ServerSend implements java.lang.Runnable {
    public Thread thread;
    public ServerSend(arg) {
        //constructor
        thread = new Thread(this);
    }
    public void run() {
        //the contents of this method are executed in their own thread
    }
}

And then use it with;

ServerSend s = new ServerSend(arg);
s.thread.start();

Public access to thread allows you to do things like;

s.thread.interrupt();

This is my preferred method (using Runnable) others prefer to extend Thread. This answer pretty much sums up my thinking: https://stackoverflow.com/a/541506/980520

Community
  • 1
  • 1
lynks
  • 5,599
  • 6
  • 23
  • 42