简体   繁体   English

在不冻结线程的情况下ping服务器

[英]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: 你有下一个选择:

  • Wait till ping ends 等到ping结束
  • Don't wait... and don't got result 不要等......而且没有结果
  • Use some concurrency classes like Future<> to got result (but you will block thread at moment you ask result if it not retrieved yet) 使用一些并发类(如Future <>)来获得结果(但如果尚未检索结果,您将在询问结果时阻止线程)
  • Or you can use some 'callback' function/interface to threw result from inner 'ping' thread. 或者你可以使用一些'回调'函数/接口从内部'ping'线程中抛出结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM