How to receive 2 thread response and store in one method?

Asked

Viewed 47 times

0

The problem is this: I have a server that receives 2 players (each in a thread) using TCP/IP. In the run of each thread they inform the move (stone, paper or scissors). I have a class "Play", which has the method "evaluate" where it should receive the play of these 2 players and compare who won.

The idea is that the constructor of the class played gets the answer from the two clients, and send both to the "evaluate" method, but I have no idea how to do this.

Or if there is a simpler solution...

I tried to put 2 players in the same thread, but I don’t know how to put more than one element in a thread...

Thank you for your patience!

SERVER:

public void startServer() throws IOException, InterruptedException {

        servidor = new ServerSocket(6789);
        System.out.println("Servidor iniciado!");
        while (true) {
            // aceita a conexao de um cliente
            cliente = servidor.accept();
            // precisa salvar a msg do cliente em jogada1
            BufferedReader leitura = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
            // recebe a jogada do jogador
            String s = leitura.readLine();
            // recebe as 2 jogadas de maneira assincrona
            // envia a jogada aos respectivos metodos call
            Future<String> jogada1 = pool.submit(new Jogada(s));
            Future<String> jogada2 = pool.submit(new Jogada(s));

            pool.shutdown();

            try {
                pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                // esses dois tambem nao sao exibidos
                String jogadaFeita1 = jogada1.get();
                String jogadaFeita2 = jogada2.get();

                System.out.println("Jogada1: " + jogadaFeita1);
                System.out.println("Jogada2: " + jogadaFeita2);
            } catch (InterruptedException | ExecutionException e) {
                Thread.currentThread().interrupt();
            }
        }

    } 

Class MOVE, which implements CALLABLE:

public class Jogada implements Callable<String>{

    String jogada;

// onde recebe a jogada
    public Jogada(String jogada) {
        this.jogada = jogada;
    }

    @Override
    public String call() throws Exception {

        System.out.println("Jogador escolheu: " + jogada);

        return jogada;
    }

}

1 answer

0

In my opinion, the simplest is to implement the interface Callable<T> in place of Runnable and use of the class Future java.

In the example below, I am using the Executors to initiate a pool of 2 threads.

The class JogadaInput is basically your class Jogada, however, implementing the interface Callable<String> which allows running in parallel and returns a Future<String>.

Note that the code blocks parallelism at the time of .get() of the object Future, therefore the .get() should only be done after submitting the two threads at the pool.

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //Recebe as duas jogadas de maneira assíncrona
        Future<String> jogada1 = executorService.submit(new JogadaInput());
        Future<String> jogada2 = executorService.submit(new JogadaInput());

        executorService.shutdown();
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

            //Obtém as jogadas feitas na outra thread.
            String jogadaFeita1 = jogada1.get();
            String jogadaFeita2 = jogada2.get();
        } catch (InterruptedException | ExecutionException e) {
            Thread.currentThread().interrupt();
        }
  • Hello, thanks for the help! A question. How can I put each move in their respective String Form? Example: Player 1’s move in "play1" and player 2’s move in "play2". The way it is, it gets an entry and displays that same entry in both gets. I modified my code in the topic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.