线程是否停止执行并继续?这简直令人困惑

时间:2014-07-18 14:58:06

标签: android client-server

我在代码中添加了日志,只是为了理解其执行的顺序和时间,但到目前为止只是让人感到困惑!

当我执行此代码并启动服务器时,我得到了这些输出


"启动服务器"," ServerThread"

"倾听"," ServerThread"

"连接到达"," ServerThread"


然后停在那里,当我连接到服务器时,我只得到


"接受连接"," ServerThread"


好像它挂在

socket = serverSocket.accept();

它是否支持退出尝试以获得某种异常并再次打印整个内容?

class ServerThread implements Runnable {

    public void run() {
        Socket socket = null;
        try {
            Log.e("start server", "ServerThread");
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("IO error at starting server", "ServerThread");
        } catch (Exception e) {
            Log.e("Exc at starting server", "ServerThread");
        }
        while (!Thread.currentThread().isInterrupted()) {
            Log.e("listening", "ServerThread");
            try {
                Log.e("connection arrived", "ServerThread");
                socket = serverSocket.accept();
                Log.e("connection accepted", "ServerThread");
                CommunicationThread commThread = new CommunicationThread(
                        socket);
                new Thread(commThread).start();

            } catch (IOException e) {
                e.printStackTrace();
                Log.e("IO error at accept", "ServerThread");
            } catch (Exception e) {
                Log.e("Exc at accept", "ServerThread");
            }
        }

    }
}

1 个答案:

答案 0 :(得分:1)

这是一种阻止方法,它将阻止,直到您收到连接。

查看文档:{​​{3}}