[英]Ping a server without freezing the Thread
I tried to use multiple threads, sadly no luck: 我试图使用多个线程,遗憾的是没有运气:
public synchronized boolean pingServer(final String ip, final short port) {
final boolean[] returnbol = new boolean[1];
Thread tt = new Thread(new Runnable() {
@Override
public void run() {
try {
Socket s = new Socket(ip, port);
s.close();
returnbol[0] = true;
} catch (IOException e) {
returnbol[0] = false;
}
}
});
tt.start();
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
tt.stop();
return returnbol[0];
}
The main thread still Freezes for some reason. 由于某种原因,主线程仍然冻结。
Is there a "lagless" way to ping a server? ping服务器有“无法”的方法吗?
You will need to remove the following lines from your code. 您需要从代码中删除以下行。 The tt.join() will force the main thread to wait for tt to finish. tt.join()将强制主线程等待tt完成。
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
tt.stop();
Use a Future instead to get the result for later use 使用Future来获取结果供以后使用
What exactly did you want to got in 你究竟想要得到什么?
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
block? 块? Here you joined to parallel thread and waits till this thread will ends (got ping result). 在这里你加入了并行线程并等待这个线程结束(获得ping结果)。
You have next options: 你有下一个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.