这是我的运行方法,它打开一个套接字,并等待接受的连接,如果连接被接受,将有一个单独的线程打开执行它:
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();
}当用户调用它来停止时,他们调用这个方法来改变while循环条件。为了打破while循环:
public void stopWorking() {
isKeepRun = false;
}那么,WorkTask的运行方法非常简单:
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();
}问题是假设读取一条消息需要每条消息1秒,用户可能会放弃100条消息,这意味着它需要100秒才能在套接字中运行。当isKeepRun继续运行时,没有问题。但是,当用户想要停止并调用stopWorking时,循环将被转义,在WorkTask正在读取消息期间套接字是否可以关闭。如果套接字仍在读取,如果套接字完成读取,并且将立即调用stopWorking,但是如果套接字没有任何要读取的内容,我该如何延迟stopWorking的执行?我可以在no中调用stopWorking延迟?
谢谢。