如何确保多个线程按顺序运行来自不同类的方法?

时间:2015-05-29 23:36:35

标签: java multithreading sockets

我正在制作一个程序,服务器为任意数量的客户提供测验。我必须使用套接字来实现这一点,所以我试图通过在我的服务器类中使用套接字对象创建多个线程来解决这个问题,每个套接字都保持与一个客户端的连接。

在我进行一些重构之前一切正常,之后我通过调试发现客户端和服务器之间的信息是按照正确的顺序发送的。

这是我的客户端线程的代码。它是我this.props.onWordToggle类的内部类,Server是其中的一个属性。

questionList

以下是我private class ClientThread implements AutoCloseable, Runnable { private Socket clientConnection; private DataOutputStream output; private DataInputStream input; public ClientThread(Socket clientConnection) throws IOException { this.clientConnection = clientConnection; output = new DataOutputStream(clientConnection.getOutputStream()); output.flush(); input = new DataInputStream(clientConnection.getInputStream()); } public void sendQuestion() throws IOException { if (input.available() > 0) if (input.readBoolean()) { Question question = questionList.get((int) (Math.random() * questionList.size())); sendQuestionInfo(question); } } private void sendQuestionInfo(Question question) throws IOException { sendInfo(question.getAuthor()); sendInfo(question.getTitle()); } private void sendInfo(String info) throws IOException { output.writeUTF(info); output.flush(); } @Override public void run() { try { sendQuestion(); } catch (IOException e) { e.printStackTrace(); } } @Override public void close() {...} } 班的相关代码:

Client

预期的执行顺序为public class QuizClient implements AutoCloseable { private Socket serverConnection; private DataOutputStream output; private DataInputStream input; public QuizClient(String serverAdress, int portNumber) throws IOException { serverConnection = new Socket(serverAdress, portNumber); output = new DataOutputStream(serverConnection.getOutputStream()); output.flush(); input = new DataInputStream(serverConnection.getInputStream()); } public void getQuiz() {...} private void playQuiz(boolean firstRun, Scanner scanner) throws IOException {...} private boolean playQuizTurn(Scanner scanner) throws IOException {...} private boolean isFirstRun() {...} private void askQuestion(Scanner scanner) throws IOException { output.writeBoolean(true); output.flush(); Question question = getQuestion(); question.quizMe(scanner); } private Question getQuestion() throws IOException { String author = input.readUTF(); String title = input.readUTF(); return new Question(author, title); } @Override public void close() throws IOException {...} } ,但使用当前代码时,它会像askQuestion() -> sendQuestion() -> getQuestion()一样运行,程序最终无法响应。

如何控制住这个?

1 个答案:

答案 0 :(得分:-1)

如果ClientThread.sendQuestion()为0,则服务器的input.available()方法将以静默方式退出 - 也就是说,如果尚未从客户端收到“true” - 这通常是新建客户端的情况。尝试让它耐心等待,直到有可用的数据,看看你是否还有进一步。