Java启动两个线程? [英] Java starting two threads?
本文介绍了Java启动两个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 新手.我有两个类,看起来像:
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.
这是我的主要课程:
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
推荐答案
用 tClient.start()
和 tServer.run 替换
和 tClient.run()
()tServer.start()
.
调用run
方法直接在当前线程中执行,而不是在新线程中执行.
Calling the run
method directly executes it in the current thread instead of in a new thread.
这篇关于Java启动两个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文