简体   繁体   中英

How to I call a function to delay execute because of some conditions in java?

This is my run method, it opens a socket, and waiting for an accepted connection, if connection is accepted, will have a separate Thread open for execute it:

while (isKeepRun) {

    socket = serverSocket.accept();

    WorkTask worktask = new WorkTask();
    worktask.setSocket(socket);
    worktask.setIn(new ObjectInputStream(socket.getInputStream()));
    worktask.setOut(new ObjectOutputStream(socket.getOutputStream()));

    Thread wt = new Thread(worktask);
    wt.start();


}


if (socket != null) {
    socket.close();
}

if (serverSocket != null) {
    serverSocket.close();
}

When the user call it to stop, they call this method, to change the while loop condition. in order to break the while loop:

public void stopWorking() {
    isKeepRun = false;
}

Well, the WorkTask's run method is very simple like that:

    try {

        do {
            objectOutputStream.flush();
            receivedObj = objectInputStream.readObject();

            if (receivedObj != null){
                System.out.println(receivedObj.toString()+"             " + receivedObj.hashCode());
            }

        } while (receivedObj != null
                && !receivedObj.equals(SharedConstant.SOCKET_EOF_STRING));

        if (objectInputStream != null) {
            objectInputStream.close();
        }
        if (objectOutputStream != null) {
            objectOutputStream.close();
        }

    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

The problem is assume that reading one message need 1 second per message, the user may give up to 100 messages, that's mean it requires 100 seconds to run, in the socket. When the isKeepRun is keep running, there is no problem. But when the user wanna to stop , and call stopWorking, the loop will be escaped, can the socket is closed, during the WorkTask is reading the message. How can I delay the execution of stopWorking if the socket is still reading, if the socket is finished reading, and the stopWorking will be call immediately, but if the socket don't have any thing to read, I can call the stopWorking in no delay?

Thanks.

If your worker thread is handling your client request then it should be his responsibility to close the socket connection. You should move the code that closes the accepted socket into your worker thread. Your server socket accept loop will be independent and will close as soon as the close request is made. But, the existing connections will still be valid and the worker thread can continue handling them.

You can check if there are still active worker threads around by calling their isAlive method. To do so, you need to keep track of your workers (using some list or map).

You might also use a call back mechanism for the workers, through which they can report back, when they finished their task. Before stopping, you simply check if every worker is done.

In both cases, if there are still active workers, sleep for some time, and check again, until all threads have finished.

Edit:

Vikas Nalwar made a good point about letting the workers close the socket connection. It still might be a good idea to wait for the worker threads to finish, though.

Try adding

wt.join()

after the wt.start(). This waits for thread to finish it's execution.

There is a problem in your code:

while (isKeepRun) {

socket = serverSocket.accept();
....

} ....

if (socket != null) {

socket.close();

}

You use only one socket reference for all client socket. So if there are more than one client socket, then you will only close the last socket.

As above said, you can use wt.join() to wait for the worker thread to finish, then the main thread will finish. But you have only one reference for client socket. Even you wait, you can only wait for the last socket to finish. All the previous client socket will be closed if you set it to stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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