Java开始两个线程?

时间:2015-01-07 12:17:16

标签: java runnable

我是java的新手。我有两个类看起来像:

public class hsClient implements Runnable {

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

public class hsServer implements Runnable {

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

如果我尝试以Thread开头这两个类,它就不会启动第二个线程。看起来他陷入了第一个。

这是我的主要课程:

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");
}

如果我运行我的代码,它只会在控制台上打印“Start Client”而不是“Start Server”

2 个答案:

答案 0 :(得分:11)

tClient.run()替换为tClient.start(),将tServer.run()替换为tServer.start()

调用run方法直接在当前线程中执行,而不是在新线程中执行。

答案 1 :(得分:1)

要启动线程,请使用start方法。

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

可以找到有关线程的更多信息,例如在JavaDoc