问题
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