Java starting two threads? [duplicate]

本秂侑毒 提交于 2019-12-24 04:48:06

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/27819356/java-starting-two-threads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!