我是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”
答案 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
中