Java启动两个线程?
我是java新手。我有两个类,看起来像:Java启动两个线程?,java,runnable,Java,Runnable,我是java新手。我有两个类,看起来像: public class hsClient implements Runnable { public void run() { while(true){ } } } public class hsServer implements Runnable { public void run() { while(true){ } } } 如果我尝试以线程的形式启动这两个类,则不会启动第二个线程。看起来他卡在
public class hsClient implements Runnable {
public void run() {
while(true){
}
}
}
public class hsServer implements Runnable {
public void run() {
while(true){
}
}
}
如果我尝试以线程的形式启动这两个类,则不会启动第二个线程。看起来他卡在第一个里面了
这是我的主要课程:
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");
}
如果我运行代码,它只在控制台上打印“启动客户端”,而不打印“启动服务器”将tClient.run()
替换为tClient.Start()
,将tServer.run()替换为tServer.Start()
调用run
方法直接在当前线程中执行,而不是在新线程中执行。要启动线程,请使用start
方法
Thread tClient = new Thread(client);
tClient.start(); // start the thread
关于线程的更多信息可以在中找到,例如,与tServer相同:)我不知道您使用的是什么IDE,但是如果您使用Netbeans或Eclipse,您可以使用断点检查哪里出错