2

i am new to java. I have two classes that looks like:

public class hsClient implements Runnable {

  public void run() {
    while(true){
    }
  }
}

public class hsServer implements Runnable {

  public void run() {
    while(true){
    }
  }
}

If i try to start both classes as Thread it wont start the second thread. It looks like he stuck in the first one.

This is my main class:

public static void main(String[] args) throws IOException {
        hsClient client = new hsClient();
        Thread tClient = new Thread(client);
        tClient.run();
        System.out.println("Start Client");
        hsServer server = new hsServer();
        Thread tServer = new Thread(server);
        tServer.run();
        System.out.println("Start Server");
}

If i run my code it only prints "Start Client" but not "Start Server" on the console

Mike
  • 693
  • 1
  • 13
  • 31

2 Answers2

11

Replace tClient.run() with tClient.start() and tServer.run() with tServer.start().

Calling the run method directly executes it in the current thread instead of in a new thread.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

To start a thread use the start method.

Thread tClient = new Thread(client);
tClient.start(); // start the thread

More info on threads can be found e.g. in the JavaDoc

wassgren
  • 18,651
  • 6
  • 63
  • 77